【问题标题】:How to make a dataset reactive in Shiny?如何在 Shiny 中使数据集具有反应性?
【发布时间】:2016-07-12 05:18:48
【问题描述】:

我想在我的闪亮应用程序中使用反应式数据集,以便可以根据reactiveDf 中的值重新渲染使用该数据集的任何其他对象。

在此示例中,我只输出一个表格,但在我的应用程序中,我还有其他图表和表格,其想法是仅通过子集 reactiveDf 来触发呈现。另外,我想使用dplyr 来做到这一点。

library(shiny)
library(dplyr)
ui <- shinyUI(fluidPage(
   sidebarLayout(
      sidebarPanel(
        checkboxGroupInput('Category', '',
                           unique(mtcars$carb), selected = unique(mtcars$carb))),
      # Show table of the rendered dataset
      mainPanel(
         tableOutput("df")
      )
   )
))


server <- shinyServer(function(input, output) {

  reactiveDf <- reactive({tbl_df(mtcars) %>% 
                                  filter(carb %in% input$Category)})

   output$df <- renderTable({reactiveDf})
})

shinyApp(ui = ui, server = server)

现在,当我运行这个应用程序时,我得到:

Listening on http://127.0.0.1:7032
Warning: Error in UseMethod: no applicable method for 'xtable' 
applied to an object of class "reactive"

并且tableOutput() 不显示。

【问题讨论】:

  • @cory 如果我这样做str(tbl_df(mtcars)),我会得到Classes ‘tbl_df’, ‘tbl’ and 'data.frame。您的意思是该对象应该是专有一个数据框吗?我也在我的原始应用程序中使用 ggvis,这就是我试图坚持使用 dplyr 作为子集的方式。

标签: r shiny dplyr


【解决方案1】:

反应式是一个函数...所以你需要括号...

library(shiny)
library(dplyr)
ui <- shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('Category', '',
                         unique(mtcars$carb), selected = unique(mtcars$carb))),
    # Show table of the rendered dataset
    mainPanel(
      tableOutput("df")
    )
  )
))


server <- shinyServer(function(input, output) {

  reactiveDf <- reactive({return(tbl_df(mtcars) %>% 
      filter(carb %in% input$Category))})

  output$df <- renderTable({reactiveDf()})
})

shinyApp(ui = ui, server = server)

【讨论】:

  • 谢谢,我从这里和那里粗暴地复制/粘贴并没有让我意识到我实际上是在定义一个函数并将其分配给reactiveDf
  • 绝对不直观,别心疼。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
  • 2014-04-14
  • 1970-01-01
  • 2015-06-29
  • 2020-11-20
  • 2018-12-03
  • 2021-11-19
相关资源
最近更新 更多