How to make a dataset reactive in Shiny?

I would like to use a reactive dataset in my brilliant application, so that any other objects that use this dataset can be re-mapped according to the values ​​in reactiveDf.

In this example, I only output one table, but in my application I have other charts and tables, and the idea is to trigger the rendering only by a subset reactiveDf. In addition, I would like to do this using 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)

Now, when I run this application, I get:

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

And tableOutput()not displayed.

+4
source share
1 answer

- ... ...

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)
+4

All Articles