How to create a hierarchy reactive table and menu in shiny

試著忘記壹切 提交于 2019-12-24 13:24:03

问题


I want to do a hierarchy menu with a reactive table output. I want my app to do things below:

  1. when I choose the brand = w, the model input I can choose should only be lower hierarchy of w (in this case: model should be w123 and w456), and the table output should be the subset of brand w

  2. when I choose the brand = w and model = w123 together, and table output should list the subset of brand = w & model = w123

here are my codes, could anyone help me? thanks

ui:

library(shiny)

shinyUI((fluidPage(
   titlePanel("hirearchy data group"),
   sidebarLayout
   (
   sidebarPanel
   (
   selectInput("brand",label="choice the brand",choices=c("all","w","s")),
   selectInput("model",label="choice the model",choices=c("all","w123","w456","s99","s88"))

   ),

   mainPanel
   (
   dataTableOutput("table")
   )

   ))))

server:

library(shiny)

## test dataframe
df <- data.frame(id = c("1","1","1","1","1","1","2","2","2","2"),
                 brand = c("w","w","w","s","s","s","w","w","w","s"),
                 model = c("w123","w123","w456","s99","s88","s88","w123","w456","w456","s99"),
                 amount = c(10,9,7,8,6,4,7,3,2,8))
df$id=as.character(df$id)
df$brand=as.character(df$brand)
df$model=as.character(df$model)


shinyServer(function(input, output) {
   output$table <- renderDataTable({ 
      if(input$brand!="all") {df=df[which(df$brand==input$brand),]}
      if(input$model!="all") {df=df[which(df$model==input$model),]}

   df

   })

})

回答1:


Add this code to your server:

  # This gets re-evaluated when input$brand changes
  observeEvent(input$brand, {
    brand <- input$brand

    # Available model options based on brand
    choices <- switch(brand, "w" = c("all","w123","w456"),
                             "s" = c("all","s99","s88"),
                           "all" = c("all","w123","w456","s99","s88"))

    # Update the model input object to only display wanted choices                  
    updateSelectInput(session, "model", choices = choices)
  })

In order for updateSelectInput to work, you also need to modify your server function definition to include the session object: your server definition should read as shinyServer(function(input, output, session) {.



来源:https://stackoverflow.com/questions/31501867/how-to-create-a-hierarchy-reactive-table-and-menu-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!