简体   繁体   English

R Shiny:使用reactiveTimer时保存先前的无功值

[英]R Shiny : Save previous reactive value while using reactiveTimer

Here is a toy example in which I draw a number between 1 and 10 every second, and where I would like to display those numbers only if the difference between the actual number which has just get drawn and the previous drawn number equals 1. So if the sequence of drawn numbers is : [5,7,8,2,3]. 这是一个玩具示例,其中我每秒绘制一个介于1和10之间的数字,并且只有当刚绘制的实际数字与之前绘制的数字之间的差值等于1时,我才想显示这些数字。所以,如果绘制数字的顺序是:[5,7,8,2,3]。 I want to display successively [8,3]. 我想连续显示[8,3]。 I guess it's all about reactive values and isolate function but I could not realize what I wanted. 我想这都是关于反应值和隔离功能,但我无法实现我的想法。 My failed attempts in commentaries. 我在评论中失败了。

library(shiny)


ui <- shinyUI(fluidPage(
  mainPanel(
    textOutput("time"),
    textOutput("num")
  )
))

server <- function(input, output, session) {

  autoInvalidate <- reactiveTimer(1000)
  timestamp<-reactive({
    autoInvalidate()
    Sys.time()
  })

  random_num<-reactive({
    autoInvalidate()
    sample(x=seq(1,10),size = 1,replace = FALSE,pro)
  })

# My attempt : obviously do not work
#   values <- reactiveValues(old=1)
#   observe({
#     if (random_num()==values$old) {values$display=random_num()}
#     else {values$old=random_num()}
#   })  

  output$time <- renderText({paste("time :",timestamp())})
  output$num <- renderText({paste("num :",random_num())})
  #My attempt : obviously do not work
  # output$num <- renderText({paste("num :",isolate(values$display))})
}

shinyApp(ui, server)

I know there is a question which looks like to mine, but it's quite different. 我知道有一个问题 ,它看起来像雷,但它是完全不同的。

Here is an example. 这是一个例子。

library(shiny)

old <- NULL

ui <- shinyUI(fluidPage(
  mainPanel(
    textOutput("time"),
    textOutput("num"),
    textOutput("num_raw")
  )
))

server <- function(input, output, session) {

  autoInvalidate <- reactiveTimer(1000)

  timestamp<-reactive({
    autoInvalidate()
    Sys.time()
  })

  random_num<-reactive({
    autoInvalidate()
    r <- sample(x=seq(1,10),size = 1,replace = FALSE)
  })

  observe({
    output$time <- renderText({paste("time :",timestamp())})
    r <- random_num()
    if (!is.null(old) && r - old == 1) {
      output$num <- renderText({paste("num :",r)})
    }
    output$num_raw <- renderText({paste("raw num : ", r)})
    old <<- r
  })

}

shinyApp(ui, server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM