【问题标题】:R Shiny: "global" variable for all functions in server.RR Shiny:server.R中所有函数的“全局”变量
【发布时间】:2015-10-07 13:33:41
【问题描述】:

我将 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"))
))

我在 shinyServer 函数的开头定义了df,并尝试使用&lt;&lt;- 分配更改in_data() 中的全局值。但是df 永远不会改变它的NULL 分配(所以output$frame 中的输出仍然是NULL)。有什么方法可以在 shinyServer 的函数中更改df 的整体值?然后,我想在 server.R 中的所有函数中使用df 作为上传的数据框,这样我只需调用一次input$file

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

非常感谢任何帮助!

【问题讨论】:

标签: r scope shiny


【解决方案1】:

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

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
 })
})

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

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()
  })
})

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2012-06-09
    相关资源
    最近更新 更多