问题
I want to do a hierarchy menu with a reactive table output. I want my app to do things below:
when I choose the
brand = w
, the model input I can choose should only be lower hierarchy of w (in this case:model
should bew123
andw456
), and the table output should be the subset ofbrand w
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