user1342178
user1342178

Reputation: 123

Update a data frame in shiny server.R without restarting the App

Any ideas on how to update a data frame that shiny is using without stopping and restarting the application?

I tried putting a load(file = "my_data_frame.RData", envir = .GlobalEnv) inside a reactive function but so far no luck. The data frame isn't updated until after the app is stopped.

Upvotes: 12

Views: 10423

Answers (1)

Joe Cheng
Joe Cheng

Reputation: 8061

If you just update regular variables (in the global environment, or otherwise) Shiny doesn't know to react to them. You need to use a reactiveValues object to store your variables instead. You create one using reactiveValues() and it works much like an environment or list--you can store objects by name in it. You can use either $foo or [['foo']] syntax for accessing values.

Once a reactive function reads a value from a reactiveValues object, if that value is overwritten by a different value in the future then the reactive function will know it needs to re-execute.

Here's an example (made more complicated by the fact that you are using load instead of something that returns a single value, like read.table):

values <- reactiveValues()
updateData <- function() {
  vars <- load(file = "my_data_frame.RData", envir = .GlobalEnv)
  for (var in vars)
    values[[var]] <- get(var, .GlobalEnv)
}
updateData()  # also call updateData() whenever you want to reload the data

output$foo <- reactivePlot(function() {
  # Assuming the .RData file contains a variable named mydata
  plot(values$mydata)
}

We should have better documentation on this stuff pretty soon. Thanks for bearing with us in the meantime.

Upvotes: 22

Related Questions