简体   繁体   中英

R Shiny: Store reactive expression to avoid recursion

I'm having a problem with recursion in my shiny app. Suppose my app reads a file and creates a dataset ( dataset() ). Then I have a function that processes the said dataset, creating another one ( dataset.proc() ). I can apply processing to the dataset as many times as I want (there are several processing methods). Another function keeps track of what's the latest dataset created ( dataset.current() ).

Here´sa simple example of the important part of my server.R script:

dataset <- reactive(#reads file and creates dataset)

dataset.current <- reactive ({
  if (!is.null(dataset())){
    if (!is.null(dataset.proc())) {
      return(dataset.proc())
    } else {
      return (dataset())
    }
  }
}) 

dataset.proc <- reactive(#processes dataset.current() according to user input, creates a processed dataset)

Is there any way I can 'store' dataset.proc() as a non-reactive expression to avoid the obvious error:

evaluation nested too deeply: infinite recursion

Any help would be much appreciated :)

You can use 'normal' R variables in the server code. For example,

current <- dataset() # Load initial dataset

shinyServer(function(input, output) {
  output$dataset.current <- renderDataTable({
    datatable(dataset.proc())
  })

  dataset.proc <- reactive({
    # Instead of dataset.current(), use the current variable

    # Processing ... 

    current <- data.frame("Processed")
    return(current)
  })
})

Before returning the result of the dataset.proc reactive expression, 'save' the result of the processing in the current variable. Next time, the dataset.proc expression can start from the value in current .

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