R Shiny: “global” variable for all functions in se

2019-04-16 12:48发布

问题:

I put global in quotes because I don't want it to be accessible by ui.R, just accessible throughout every function in server.R. Here's what I mean:

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

I have df defined at the beginning of the shinyServer function, and try to change its global value in in_data() with the <<- assignment. But df never changes its NULL assignment (so the output in output$frame is still NULL). Is there any way to change the overall value of df within a function in shinyServer? I want to then use df as the uploaded data frame throughout all of my functions in server.R so that I only have to call input$file once.

I looked at this post, but when I tried something similar, and error was thrown that envir=.GlobalENV wasn't found. The overall goal is to only call input$file once and use the variable the data is stored in instead of repeatedly calling in_data().

Any help is greatly appreciated!

回答1:

The idea to use reactive is the right direction; however you didn't do it quite right. I just added one line and it is working:

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

Why? Because a reactive object is very similar to a function, which gets executed only when you call it. Thus the 'standard' way of your code should be:

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


标签: r scope shiny