SNT
SNT

Reputation: 1393

Pass multiple values for each selected option in selectInput R Shiny

I am trying to combine values into one selectInput for that to be passed on to another function. So here is my code where the user selects the first input and the values should be survey = 1 and youth = FALSE.

library(shiny)

output$choose_wave <- renderUI({
  selectInput("selected_wave", "Wave", choices = list(
    "Wave 1- Adult" = wave = 1, youth = FALSE,
    "Wave 1- Youth" = wave = 1, youth = TRUE,
    "Wave 2- Adult" = wave = 2, youth = FALSE,
    "Wave 2- Youth" = wave = 2, youth = TRUE
  ))
})

What is the better way to pass two values with one input?

Upvotes: 0

Views: 1409

Answers (2)

phalteman
phalteman

Reputation: 3532

Either selectizeInput or pickerInput (part of the shinyWidgets package) will do what I think you're asking for. This is an example using pickerInput, where you can divide the two kinds of factors into groups and allow multiple selections that end up getting grouped into the output. Here is a minimal example.

devtools::install_github("dreamRs/shinyWidgets")
library(shiny)
library(shinyWidgets)
ui <- fluidPage(
  uiOutput("choose_wave"),
  h5("Value from selected wave:"),
  verbatimTextOutput("select_values")
)

server <- function(input,output) {
  output$choose_wave <- renderUI({
  pickerInput("selected_wave", "Select one from each group below:", 
          choices = list(Wave = c("Wave 1" = 1, "Wave 2" = 2), Youth = c("Adult"=FALSE, "Youth"=TRUE)),
                         multiple = T, options = list('max-options-group' = 1))
  })
  output$select_values <- renderText({as.character(input$selected_wave)})
}

shinyApp(ui, server)

UPDATE: The development version of shinyWidgets now allows limits on the number of selections per group (Thanks Victor!). Code above has been updated to limit selections to one per group, but you'll need to use the development version for it to work.

The menu layout:

enter image description here

The values:

enter image description here

Upvotes: 2

Chabo
Chabo

Reputation: 3000

Can you use an if/else? May be more bulky but it works. Also does that input work, I usually assign a value to a text input.

if(input$wave==1 #or whatever the input is actually equal too){
wave = 1
youth = FALSE
}else if(input$wave==2){
wave = 1
youth = TRUE
} and so on..

I would say assign inputs to a value first and then assign extra data you need.

Upvotes: 0

Related Questions