[英]displaying 'reactive values' in r shiny
基本思路是在值发生变化后向最终用户打印值。
提供的代码生成闪亮的仪表板,并在几秒钟后将值0输出到屏幕。 为了在打印0之前打印所有中间值(4,3,2,1),我应该更改什么? 如何最好地显示值,而不仅仅是打印?
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)
我希望输出为:
4
3
2
1
0
或包含上述内容的表,但实际输出仅为0。
这可能是一些可以帮助你的东西。 您必须在renderPrint
之外定义变量。 在我的示例中,变量是定时器触发器上的更改,但可以是任何其他输入。 代码并不完美,初始循环立即执行,你将从头开始看到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.