简体   繁体   中英

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]. I want to display successively [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)

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