R Shiny:server.R 中所有函数的“全局”变量

Kir*_*bbe 2 scope r shiny

我将 global 放在引号中,因为我不希望它可以被 ui.R 访问,而只能通过 server.R 中的每个函数访问。这就是我的意思:

shinyServer(function(input, output, session) {
  df <- NULL
  in_data <- reactive({
    inFile <- input$file1
    if (is.null(inFile)) return(NULL)     
    else df <<- read.csv(inFile$datapath, as.is=TRUE)  
    return(NULL)
   })
  output$frame <- renderTable({
    df
  })
})

shinyUI(pageWithSidebar(
   sidebarPanel(fileInput("file1", "Upload a file:",
                           accept = c('.csv','text/csv','text/comma-separated-values,text/plain'),
                           multiple = F),),
   mainPanel(tableOutput("frame"))
))
Run Code Online (Sandbox Code Playgroud)

df在shinyServer函数的开头定义了它,并尝试in_data()通过赋值来改变它的全局值<<-。但df永远不会更改其NULL分配(因此 中的输出output$frame仍然是NULL)。有什么方法可以改变dfshinyServer中函数内的总体值吗?然后我想df在 server.R 中的所有函数中用作上传的数据帧,这样我只需调用input$file一次。

我查看了这篇文章,但是当我尝试类似的操作时,抛出了错误,找不到 envir=.GlobalENV 。总体目标是仅调用input$file一次并使用存储数据的变量,而不是重复调用in_data()

任何帮助是极大的赞赏!

Cha*_*ing 5

使用响应式的想法是正确的方向;但是你做得不太对。我刚刚添加了一行并且它正在工作:

shinyServer(function(input, output, session) {
  df <- NULL
  in_data <- reactive({
    inFile <- input$file1
    if (is.null(inFile)) return(NULL)     
    else df <<- read.csv(inFile$datapath, as.is=TRUE)  
    return(NULL)
  })
  output$frame <- renderTable({
    call.me = in_data()   ## YOU JUST ADD THIS LINE. 
    df
 })
})
Run Code Online (Sandbox Code Playgroud)

为什么?因为响应式对象与函数非常相似,只有在调用它时才会执行。因此,代码的“标准”方式应该是:

shinyServer(function(input, output, session) {
  in_data <- reactive({
    inFile <- input$file1
    if (is.null(inFile)) return(NULL)     
    else read.csv(inFile$datapath, as.is=TRUE)  
  })
  output$frame <- renderTable({
    in_data()
  })
})
Run Code Online (Sandbox Code Playgroud)