我创建了以下简单的函数来在用户单击按钮时增加计数器:
observeEvent(input$go, {
counter = 1
print(counter)
counter <- (counter + 1)
print(counter)
})
Run Code Online (Sandbox Code Playgroud)
我初步counter
如下:
counter = 1
shinyServer(function(input, output) {
...
Run Code Online (Sandbox Code Playgroud)
如果我Go
多次点击按钮,我预计计数器会不断增加一个.但是,输出始终如下:
[1] 1
[1] 2
[1] 1
[1] 2
[1] 1
[1] 2
[1] 1
[1] 2
Run Code Online (Sandbox Code Playgroud)
有人能解释一下为什么吗?
尝试使用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)
Run Code Online (Sandbox Code Playgroud)