简体   繁体   English

在r闪亮中显示'反应值'

[英]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. 提供的代码生成闪亮的仪表板,并在几秒钟后将值0输出到屏幕。 What should I change in order for it to print all the intermediate values (4, 3, 2, 1) before it prints 0? 为了在打印0之前打印所有中间值(4,3,2,1),我应该更改什么? 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. 或包含上述内容的表,但实际输出仅为0。

Here is maybe something that can help you. 这可能是一些可以帮助你的东西。 You have to define a variable outside the renderPrint . 您必须在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. 代码并不完美,初始循环立即执行,你将从头开始看到5和4,但应该是一个好的开始。

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)

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

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