2016-05-09 17 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