Franco Buhay
Franco Buhay

Reputation: 3

Shiny -- how to output a reactive list?

I'm in the middle of learning shiny, and I'd like to be able to output a list in the main panel based on filter conditions specified by a checkbox group in the sidepanel.

The checkbox code looks like this:

      checkboxGroupInput("cats",
               label = "Which category would you like to see?",
               choices = list("Interest",
                              "Demographics",
                              "Travel",
                              "Retail",
                              "Financial",
                              "Lifestyle",
                              "Technology"),
               selected = c("Interest", "Demographics", "Travel", "Retail", "Financial", "Lifestyle", "Technology"))

What I'd like to know is if there's a way to view a list in the main panel based on whether these values are checked or not. That is if I have 'Demographics' and 'Travel' checked off, and my data frame looks like:

    A            B
Interest         7
Interest         2
Demographics     3
Travel           4
Financial        4
Lifestyle        6
Lifestyle        7
Technology       9

I'd like to be able to display a list in the main panel that looks like this:

B
3
4

Upvotes: 0

Views: 6540

Answers (2)

Vishesh Shrivastav
Vishesh Shrivastav

Reputation: 2129

You can use %in% to check if multiple options are selected in your checkboxGroupInput and retrieve data for selected options. Something along the lines of:

df.selected <- reactive({
        foo <- subset(YOUR.DATA(), A %in% input$cats)
        return(foo)
      })

Then, you can display df.selected()['A', 'B'] as the output by rendering it as a table.

output$table.show <- renderTable({df.selected()})

Upvotes: 0

shosaco
shosaco

Reputation: 6165

Straightforward:

library(shiny)

myData <- read.table(text = "   A            B
           Interest         7
           Interest         2
           Demographics     3
           Travel           4
           Financial        4
           Lifestyle        6
           Lifestyle        7
           Technology       9", header = TRUE, stringsAsFactors = FALSE)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(checkboxGroupInput("cats",
                                    label = "Which category would you like to see?",
                                    choices = unique(myData$A),
                                    selected = unique(myData$A))),
    mainPanel(dataTableOutput("table"))
  )
)

server <- function(input, output) {

  output$table <- renderDataTable({
    subset(myData, A %in% input$cats, select = "B")
  })
}

shinyApp(ui, server)

enter image description here

Upvotes: 1

Related Questions