Nevedha Ayyanar
Nevedha Ayyanar

Reputation: 865

Updating the choices in pickerInput 2 based on the value selected in pickerInput 1 in R

I am having two pickerInputs in the application. The snippet of the first pickerInput is as follows:

  managers <- c('Ram', 'Vijay','Arun','Aswin')
  dept <- c('A','B','C','D')
  details <- data.frame("Managers" = managers, "Department" = dept)


pickerInput(
  'manager', 'Manager',
  choices = managers ,
  c('Ram', 'Vijay','Arun','Aswin'),
  multiple = TRUE
)

The department of the corresponding managers are listed in the dataframe details

The snippet for the 2nd pickerInput is as follows:

pickerInput('dept', 'Department', choices = dept, c('A','B','C','D'), multiple = TRUE)

So, when the managers are selected from the first pickerInput, the corresponding deparments should be displayed in the choices of the second pickerInput. This should be done dynamically.

Is this possible in R? If not, is there any other alternatives to do this functionality?

Upvotes: 3

Views: 1401

Answers (1)

Florian
Florian

Reputation: 25375

You can use uiOutput and renderUI to dynamically generate the required input object. A working example is given below, hope this helps.

library(shiny)
library(shinyWidgets)

managers <- c('Ram', 'Vijay','Arun','Aswin')
dept <- c('A','B','C','D')
details <- data.frame("Managers" = managers, "Department" = dept, stringsAsFactors = F)

ui <- fluidPage(
  pickerInput(
    'manager', 'Manager',
    choices = managers ,
    c('Ram', 'Vijay','Arun','Aswin'),
    multiple = TRUE
  ),
  uiOutput('picker2')
)

server <- function(input, output, session) {
  output$picker2 <- renderUI({
    choices = details$Department[details$Managers %in% input$manager]
    pickerInput('dept', 'Department', choices = choices, choices, multiple = TRUE)
  })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions