R Shiny Server - 如何在observeEvent函数中保存变量值?

时间:2015-11-12 12:55:27

标签: r shiny

我创建了以下简单的函数来在用户点击按钮时增加计数器:

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

有人能解释我为什么吗?

1 个答案:

答案 0 :(得分:5)

尝试将observeEventreactiveValues一起使用。下面的最小工作示例:

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)