我可以在响应对象更改时保存它的旧值吗? [英] Can I save the old value of a reactive object when it changes?

查看:40
本文介绍了我可以在响应对象更改时保存它的旧值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:在想出答案后,我改写了问题,以便更清楚.

Note: After coming up with the answer I reworded the question to make if clearer.

有时在 shiny 应用中.我想利用用户为小部件选择的值,以及为同一小部件​​选择的先前值.这适用于从用户输入派生的反应值,我想要旧值和新值.

Sometimes in a shiny app. I want to make use of a value selected by the user for a widget, as well as the previous value selected for that same widget. This could apply to reactive values derived from user input, where I want the old and the new value.

问题是,如果我尝试保存小部件的值,那么包含该值的变量必须是反应性的,否则每次小部件更改时它都不会更新.但是,如果我将值保存在响应式上下文中,它将始终为我提供当前值,而不是前一个值.

The problem is that if I try to save the value of a widget, then the variable containing that value has to be reactive or it will not update every time the widget changes. But, if I save the the value in a reactive context it will always give me the current value, not the previous one.

如何保存小部件的先前值,但每次用户更改小部件时仍然更新它?

How can I save the previous value of a widget, but still have it update every time the user changes the widget?

有没有一种方法不需要每次用户更改时都使用 actionButton ?避免 actionButton 可能是可取的,否则添加一个是不必要的,并且会为用户带来过多的点击.

Is there a way that does not require the use of an actionButton every time the user changes things? Avoiding an actionButton can be desirable with adding one is otherwise unnecessary and creates excess clicking for the user.

推荐答案

鉴于会话刷新事件方法似乎为此目的而被破坏,这里是使用 observeEvent 的替代方法构造和反应变量.

Seeing as the session flush event method seems to be broken for this purpose, here is an alternative way to do it using an observeEvent construct and a reactive variable.

library(shiny)

ui <- fluidPage(
  h1("Memory"),
  sidebarLayout(
    sidebarPanel(
      numericInput("val", "Next Value", 10)
    ),
    mainPanel(
      verbatimTextOutput("curval"),
      verbatimTextOutput("lstval")
    )
  )
)

server <- function(input,output,session) {
  rv <- reactiveValues(lstval=0,curval=0)

  observeEvent(input$val, {rv$lstval <- rv$curval; rv$curval <- input$val})

  curre <- reactive({req(input$val);  input$val; rv$curval})
  lstre <- reactive({req(input$val);  input$val; rv$lstval})

  output$curval <- renderPrint({sprintf("cur:%d",curre())})
  output$lstval <- renderPrint({sprintf("lst:%d",lstre())})
}
options(shiny.reactlog = TRUE)
shinyApp(ui, server)

产量:

这篇关于我可以在响应对象更改时保存它的旧值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆