简体   繁体   中英

R Shiny: reactivevalues from function

I stored several tables in .rds files which I would like to import using readRDS in a Shiny session. Therefore I defined the following global function:

get.station <- function(sname){
  file.name <- paste(sname".rds", sep="")
  return(readRDS(file.name))
}

within the server function I define the reactive value:

st.reactive <- reactiveValues(get.station(input$station.sel))

where input$station.sel comes from the ui using selectInput(...) . This results in the following error message:

Operation not allowed without an active reactive context. 
(You tried to do something that can only be done from inside 
a reactive expression or observer.)

This error message even does not disappear if I define this function using reactive() :

get.station <- reactive({
    file.name <- paste(input$station.sel".rds", sep="")
    return(readRDS(file.name))
  })

and within the server:

st.reactive <- reactiveValues(data=get.station())

Do you have any help?

You've got the right idea, just put the function inside a reactive or observe_ function. While you can define reactiveValues in the initial call, its best, in my opinion, to create the reactive values object empty and then do all your assignments with the <- notation.

The confusion comes from the fact that, despite it's name, reactiveValues is not a reactive expression. It generates a reactiveValues object that reactive values can be stored in, but it only runs once and does not check whether its values are invalidated.

In your case, I'd do the following:

rv <- reactiveValues()
rv$st.reactive <- observe({get.station(input$station.sel)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM