简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM