简体   繁体   中英

displaying 'reactive values' in r shiny

The basic idea is to print a value to the end user once the value has changed.

The provided code, generates a shiny dashboard and prints the value 0 to the screen after some seconds. What should I change in order for it to print all the intermediate values (4, 3, 2, 1) before it prints 0? And how would it be best to display the values, rather than just printing?

library(shiny)
library(shinydashboard)
x = 5

ui <- dashboardPage(
  dashboardHeader(title = "test"),
  dashboardSidebar(),
  dashboardBody(textOutput(outputId = "out"))
)

server <- function(input, output){
  while(x > 0){
    x = x - 1
    Sys.sleep(1)
    output$out <- renderPrint(x)
  }
}

shinyApp(ui, server)

I expect the output to be:

4
3
2
1
0

or a table containing the above, but the actual output is just 0.

Here is maybe something that can help you. You have to define a variable outside the renderPrint . In my example the variable is change on a timer trigger, but can be any other input. The code is not perfect, the initial loop is executed immediately and you will see 5 and 4 from the beginning, but should be a good start.

library(shiny)
library(shinydashboard)
x = 5

ui <- dashboardPage(
  dashboardHeader(title = "test"),
  dashboardSidebar(),
  dashboardBody(
    textOutput(outputId = "out"),
    verbatimTextOutput(outputId = "outText"),
    tags$hr(),
    actionButton("go","Change value on click"),
    verbatimTextOutput(outputId = "out2")
    )
)

server <- function(input, output){

  # define reactive variable
  outVar <- reactiveValues(dataRow=x,
                           text=paste(x),
                           value = x)
  # define time dependent trigger
  autoInvalidate <- reactiveTimer(2000) 

  # render print
  output$out <- renderPrint(outVar$dataRow)
  # render text print
  output$outText <- renderText(outVar$text)
  # render print
  output$out2 <- renderText(outVar$value)


  # time dependent change of variable
  observeEvent(autoInvalidate(),{
    # check if > 0 
    if(outVar$dataRow[length(outVar$dataRow)] > 0){
      # add
      outVar$dataRow <- c(outVar$dataRow,outVar$dataRow[length(outVar$dataRow)]-1)
      outVar$text <- paste0(outVar$text,'\n',outVar$dataRow[length(outVar$dataRow)])
    }
  })

  # observer on click button
  observeEvent(input$go,{
    # check if > 0 
    if(outVar$value > 0){
      # lower by one
      outVar$value <- outVar$value - 1
    }
  })
}

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