【问题标题】:eventReactive in shiny doesn't update data闪亮的 eventReactive 不会更新数据
【发布时间】:2015-09-21 17:48:57
【问题描述】:

在我下面的示例中,一旦在 RStudio 中运行,通过单击滑块上的“播放”按钮,移位的行数逐渐增加。但是通过暂停,然后将数据集名称更改为iris,然后单击“显示”按钮并重新单击“播放”,不会出现相同的动画行数增加...为什么?以及如何调整我的代码来做到这一点......即让动画出现在不同的数据集上?

下面的例子部分改编自eventReactive()函数

require(shiny)
if (interactive()) {
  ui <- fluidPage(
    column(4,
           sliderInput('x',label='Num Rows',min=2,max=30,step=1,value=3,animate = TRUE),
           textInput('tbl_nm',label='Data Set',value='cars'),
           br(),
           actionButton("button", "Show")
     ),
     column(8, tableOutput("table"))
   )
   server <- function(input, output) {

    # reactively adjust the number of rows
    ll <- eventReactive(input$x,{
      input$x
    })


    # change the data sets after clicking the button
    dat <- eventReactive(input$button,{
       if(input$tbl_nm=='cars'){
         dat <- cars
      } else {
         dat <- get(input$tbl_nm)
      }
      return(dat)
     })

    # Take a reactive dependency on input$button, but
    # not on any of the stuff inside the function
    df <- eventReactive(input$button, {
       yy <- ll()
      # choose only the relevant data...
      head(dat(),yy)
    })

    # show the final table
    output$table <- renderTable({

      if(input$button==0){
        # show the first few lines of cars at the begining
        head(cars, ll())
      } else {
        # show the selected data
        df()
      }

    })
  }


  shinyApp(ui=ui, server=server)
}

【问题讨论】:

    标签: r rstudio shiny


    【解决方案1】:

    发生这种情况的原因是:

    output$table <- renderTable({
    
      if(input$button==0){
        # show the first few lines of cars at the begining
        head(cars, ll())
      } else {
        # show the selected data
        df()
      }
    
    })
    

    每次按下按钮时,其值 (input$button) 都会增加 1。应用打开时只有0。所以, head(cars, ll()) 仅在第一次按下按钮之前运行。之后,input$button 递增,其值为 2、3、4、...等。

    ll() 是一个依赖于input$x(您的滑块)的事件响应式。因此,当您的滑块更新或按下播放标志时,ll() 会更新,并且您的表格会重新显示。

    在第一次按下后,df() 将改为运行。这是一个依赖于input$button 的事件响应 - 它仅在按下按钮时运行。在按下按钮之前,您的表格将无法更新。

    要解决此问题,您可以使用:

    df <- eventReactive(input$button | input$x, {
      yy <- ll()
      # choose only the relevant data...
      head(dat(),yy)
    })
    

    改为你的df()。现在,如果按下按钮或滑块更新,它将更新

    【讨论】:

      猜你喜欢
      • 2015-10-27
      • 2020-12-04
      • 2021-02-13
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 2019-03-18
      相关资源
      最近更新 更多