I want to be able to have UI inputs in shiny that update themselves based on the previous choices of a user. So in the example below, the intended behavior would be that the user chooses from cyl, vsor carbwhich will then
- filter the dataset
mtcarswhich is used to create a plot i.e. the user adjusts the plot to the filter criteria and - update the remaining input choices in the other filters in order to correspond to the remaining choices based upon the filter that is already in place.
Here is what I tried:
library(shiny)
library(dplyr)
library(plotly)
data("mtcars")
# create ui
ui <- fluidPage(
fluidRow(
box(
title = "Filter",
uiOutput(outputId = "cyl_dynamic_input"),
uiOutput(outputId = "vs_dynamic_input"),
uiOutput(outputId = "carb_dynamic_input")
),
box(
title = "Plot of mtcars",
plotlyOutput("carplot")
)
),
)
# create server
server <- function(input, output, session) {
# create reactive filters of the mtcars table
mtcars.reactive <-
reactive({
mtcars %>%
filter(mpg %in% input$cyl_input_rendered &
vs %in% input$vs_input_rendered &
carb %in% input$carb_input_rendered
)})
## create rendered inputs
# for cyl
output$cyl_dynamic_input <- renderUI({
pickerInput(inputId = "cyl_input_rendered",
label = "CYL",
choices = unique(mtcars$cyl),
multiple = T,
selected = mtcars.reactive()$cyl,
options = list(
`actions-box` = TRUE,
`selected-text-format`= "count",
`count-selected-text` = "{0} out of {1} cyl selected"
))
})
# for vs
output$vs_dynamic_input <- renderUI({
pickerInput(inputId = "vs_input_rendered",
label = "VS",
choices = unique(mtcars$vs),
multiple = T,
selected = mtcars.reactive()$vs,
options = list(
`actions-box` = TRUE,
`selected-text-format`= "count",
`count-selected-text` = "{0} out of {1} vs selected"
))
})
# for carb
output$carb_dynamic_input <- renderUI({
pickerInput(inputId = "carb_input_rendered",
label = "CARB",
choices = unique(mtcars$carb),
multiple = T,
selected = mtcars.reactive()$carb,
options = list(
`actions-box` = TRUE,
`selected-text-format`= "count",
`count-selected-text` = "{0} out of {1} carb selected"
))
})
## create the plot output
# Start Barplot Emissionen here
output$carplot<-
renderPlotly({
# create plot
plot<-ggplot(mtcars.reactive(), aes(wt, mpg))+
geom_point()
# convert to plotly
ggplotly(plot)
})
}
shinyApp(ui, server)
My guess is that the this cannot work because the filter for the mtcarstable references to the rendered inputs and vice versa which somehow creates an empty information loop
I already had a look in the official Shiny documentation which also provides some background information but the whole topic is not really intuitiv for a beginner. Here is a somehow similar question but it is not fully reproducible.
pickerInputbased on the selected value of another, you need to useupdatePickerInputinside a reactive (observeEvent, say) that responds to a change in the definingpickerInput. There's no need to useuiOutput/renderUI.