I am trying to create two dropdowns based on user input. If a user selects "val1", then show values in the second dropdown from "x". If "val2", then "y". If both "val1" and "val2", then z.
So far, I succeeded except for the multiple selection part. I also tried:
else if (input$lab == "val1" & input$lab == "val2")
which gives me the same error:
the condition has length > 1 and only the first element will be used
x <- c("x1", "x2", "x3")
y <- c("y1", "y2", "y3")
z <- c("x1", "x2", "x3", "y1", "y2", "y3")
library(shiny)
library(shinydashboard)
library(shinyWidgets)
ui <- dashboardPage(
dashboardHeader(title = "title"),
dashboardSidebar(
sidebarMenu(
menuItem("xxx", tabName = "tab1")
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "tab1",
pickerInput("dropdown1", "Values:", choices = c("x", "y"), multiple = T),
uiOutput("dropdown2")
)
)
)
)
server <- function(input, output, session) {
values <- reactive({
req(input$dropdown1)
if (input$dropdown1 == "x") {
x
}
else if (input$dropdown1 == "y") {
y
}
else if (input$dropdown1 == "x" && input$dropdown1 == "y") {
z
}
})
output$dropdown2 <- renderUI({
pickerInput("dropdown2", "Values:", choices = values())
})
}
shinyApp(ui, server)
CodePudding user response:
Slight change in approach in your server. Rather than ifelse to test for for x, y, or x&y, you can instead test for length == 1 and then within that case, whether it's x or y.
server <- function(input, output, session) {
values <- reactive({
req(input$dropdown1)
if (length(input$dropdown1) == 1) {
if (input$dropdown1 == "x") {
"x"
}
else {
"y"
}
}
else {
"z"
}
})
output$dropdown2 <- renderUI({
pickerInput("dropdown2", "Values:", choices = values())
})
}
Depending on what really will go in "x" and "y", using ifelse()
might save you space in this approach.