2016-05-09 15 views
1

我的反应式表达式产生一个数值向量。有没有办法可以保存之前渲染的值并在下次重新使用它?我试图创建一个额外的反应表达式中使用的第一反应表达时保存的值,然后再调用它,但是这将导致以下错误:如何在反应性表达式中使用以前的反应值?

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

我不能上传我的整个的例子,因为它是一个调查,是一种保密。但是,我试图给我的server.R文件的见解。

yvals  <- reactive({...}) 

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

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

问题是,yvals是基于ui.R的输入。但是,xvals不是(至少不是直接)。所以当xvals正在更新时,它应该将旧/旧值作为输入。我对这个烂摊子感到抱歉 - 我意识到,如果没有可重复的例子,这很难帮助我。但基本上,我只想修复之前的反应结果,并在下次重新使用它。

+0

请提供你正在试图完成一个例子。请参阅以下文章,提供[可重现的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – lmo

+1

[可以保存反应对象的旧值时它可以保存吗?](http://stackoverflow.com/questions/26432789/can-i-save-the-old-value-of-a-reactive -object-when-it-changes) –

+1

我认为你正在寻找'reactiveValues',但我会等待在回答之前看到你的可重现的例子。 – Pete900

回答

1

有点晚了,但我认为这是你想要的 - 这是一个很好的excersize。它使用反应变量memory来跟踪一次迭代到下一次迭代。注意isolate表达式避免了递归错误。

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) 

图片:

enter image description here