Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 基本局部作用域对象_R_Shiny_Scoping - Fatal编程技术网

R 基本局部作用域对象

R 基本局部作用域对象,r,shiny,scoping,R,Shiny,Scoping,我希望在每个会话中都有一个局部变量,该变量可以通过输入进行更新,服务器中的所有其他函数都可以使用该变量。请参见下面的简单示例,我希望在用户更改值但不更改时更新对象 library(shiny) # Define UI for application ui = shinyUI(pageWithSidebar( # Application title headerPanel("Hello Shiny!"), # Sidebar with a slider input for data

我希望在每个会话中都有一个局部变量,该变量可以通过输入进行更新,服务器中的所有其他函数都可以使用该变量。请参见下面的简单示例,我希望在用户更改值但不更改时更新对象

library(shiny)

# Define UI for application  

ui =  shinyUI(pageWithSidebar(

# Application title
headerPanel("Hello Shiny!"),

# Sidebar with a slider input for data type
sidebarPanel(
  selectInput("data", 
            "Pick letter to us in complex app?", choices = c("A","B"),
             selected = "A")
  ),

# Print letter
 mainPanel(
   textOutput("Print")
 )
))


server =shinyServer(function(input, output) {
  MYLetter = "A";
  updateData = reactive({
    if (input$data == "A") {
      MYLetter <<- "A"
    } else {
      MYLetter <<- "B"
    }
  })
  output$Print <- renderText({ 
    print(MYLetter)
  })
})

shinyApp(ui, server)

我觉得解决方案是全局变量,但如果两个人同时在应用程序上。一个人给一个全局变量分配一个新值会改变另一个用户的变量吗?

您的代码有几个问题。以下是您想要的代码,我尝试对您的代码进行非常小的更改以使其正常工作:

ui =  shinyUI(pageWithSidebar(

    # Application title
    headerPanel("Hello Shiny!"),

    # Sidebar with a slider input for data type
    sidebarPanel(
        selectInput("data", 
                    "Pick letter to us in complex app?", choices = c("A","B"),
                    selected = "A")
    ),

    # Print letter
    mainPanel(
        textOutput("Print")
    )
))


server =shinyServer(function(input, output) {
    MYLetter = reactiveVal("A");
    observe({
        if (input$data == "A") {
            MYLetter("A")
        } else {
            MYLetter("B")
        }
    })
    output$Print <- renderText({ 
        print(MYLetter())
    })
})

shinyApp(ui, server)
基本上,这两个问题是:

您正在寻找的是使用reactiveVal或reactiveValues创建一个被动值。您完全正确地认为创建全局变量不是正确的解决方案,因为这样它将在所有用户之间共享。它也不是那样的反应

我将反应式{…}更改为观察式{…}。理解被动和观察者之间的区别是非常重要的。我建议上网阅读。我将其更改为观察,因为您没有返回正在使用的值,而是在其中进行赋值