我创建了以下简单的函数来在用户点击按钮时增加计数器:
observeEvent(input$go, {
counter = 1
print(counter)
counter <- (counter + 1)
print(counter)
})
我初始化counter
如下:
counter = 1
shinyServer(function(input, output) {
...
如果我多次点击Go
按钮,我预计计数器会不断增加一个。但是,输出始终如下:
[1] 1
[1] 2
[1] 1
[1] 2
[1] 1
[1] 2
[1] 1
[1] 2
有人能解释我为什么吗?
答案 0 :(得分:5)
尝试将observeEvent
与reactiveValues
一起使用。下面的最小工作示例:
library(shiny)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("go", "Go")
),
mainPanel(
verbatimTextOutput("text")
)
)
))
server <- shinyServer(function(input, output) {
v <- reactiveValues(counter = 1L)
observeEvent(input$go, v$counter <- v$counter + 1L)
output$text <- renderPrint({
print(v$counter)
})
})
shinyApp(ui = ui, server = server)