简体   繁体   中英

How can I use a previous reactive value in a reactive expression in shiny?

My reactive expression produces a vector of numeric values. Is there a way that I can save the previous rendered values and re-use it the next time? I tried to create an additional reactive expression to save the values and then call it again when using the first reactive expression but that causes the following error:

Error in : evaluation nested too deeply: infinite recursion / options(expressions=)?

I cannot upload my entire example since it is a survey, which is kind of confidential. However, I am trying to give insights into my server.R file.

yvals     <- reactive({...})

xvals     <- c(...) #some default values to start with

xvals     <- reactive({
             dat <- data.frame(xvals(), yvals())
             ....
             print(xvals)
             })

The issue is that yvals is based on the inputs of ui.R. However, xvals is not (at least not directly). So when xvals is updating it should take the old/previous values as input. I'm sorry for the mess - I'm aware that it is hard to help me without reproducible example. But basically, I just want to fix the previous reactive result and re-use it the next time.

A bit late, but I think this is what you want - it was a good excersize. It uses a reactive variable memory to keep track from one iteration to the next. Note the isolate expression avoids the recursion error.

library(shiny)

ui <- fluidPage(
  h1("Reactive Memory"),
  sidebarLayout(
    sidebarPanel(
      numericInput("val","Next Value",10)
    ),
    mainPanel(
      verbatimTextOutput("prtxval")
    )
))
server <- function(input,output,session) {

  nrowsin <- 6
  ini_xvals <- 1:nrowsin

  memory <- reactiveValues(dat = NULL)
  yvals <- reactive({ rep(input$val,nrowsin) })

  xvals <- reactive({

    isolate(dat <- memory$dat)
    if (is.null(dat)) {
      memory$dat <- data.frame(xvals = ini_xvals,yvals())
    } else {
      memory$dat <- data.frame(dat,yvals())
    }
    return(memory$dat)
  })

  output$prtxval <- renderPrint({ xvals() })
}
shinyApp(ui,server)

Picture:

在此处输入图片说明

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