Dambo
Dambo

Reputation: 3486

How to make a dataset reactive in Shiny?

I would like to use a reactive dataset in my shiny app, such that any other objects that uses that dataset can be re-rendered according to the values in reactiveDf.

In this example I am outputting only one table, but in my app I have other charts and tables, and the idea is to trigger the rendering by subsetting reactiveDf only. Also, I would like to do that 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)

Right now, when I run this app 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() is not displayed.

Upvotes: 5

Views: 4821

Answers (1)

cory
cory

Reputation: 6659

A reactive is a function... so you need parens...

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)

Upvotes: 6

Related Questions