Dynamic Reactive UI - updating inputs and saving selected objects

I have an app which utilizes a dynamic UI based on how many predictors the user selects. However, I am running into three issues that I can't figure out how to get around. Can anyone tell me:

(1) How I make the parameter choices dependent on the predictor selected? For example, if the user selects 'mpg', then the parameter options should be {1, 2}; if the user selects 'cyl' then {3, 4}, and if the user selects 'disp' then {5,6}.

(2) How can I ensure that subsequent predictors options omit previously selected predictors. For example, if the user selects 'mpg' for Predictor 1, then only 'cyl' and 'disp' will be available as choices for Predictor 2, etc.

(3) Is there any way to keep the values selected as predictors are added or subtracted? Each time the number of predictors changes, the selected options revert back to default. I have tried using 'isolate' here but that is not working.

Thanks so much for any help anyone can offer on any of these!

## libraries
library(tidyverse)
library(shiny)

## variable names
var_names <- colnames(mtcars[,1:3])

ui <- fluidPage(
  ## input selector for number of predictors
  numericInput(inputId = "n_preds", 
               label = "Number of Predictors", 
               value = 1, 
               min = 1,
               max = length(var_names)),
  ## stored ui object
  fluidRow(column(3, uiOutput("preds")),
           column(3, uiOutput("params"))
  )
)

server <- function(input, output, session) {
  ## create objects to store individual predictors
  predictors <- reactive(paste0("Predictor ", seq_len(input$n_preds), ":"))
  output$preds <- renderUI({
    map(predictors(), ~ selectInput(inputId = .x, 
                                    label = .x, 
                                    choices = var_names, 
                                    selected = var_names[1]))
  })
  ## create objects to store individual predictors options
  parameters <- reactive(paste0("Parameter ", seq_len(input$n_preds), ":"))
  output$params <- renderUI({
    map(parameters(), ~ selectInput(inputId = .x, 
                                    label = .x, 
                                    choices = var_names, 
                                    selected = var_names[1]))
  })
}

shinyApp(ui, server)

Have you read https://mastering-shiny.org/action-dynamic.html? At a minimum it solves 3, and I suspect will help with your other questions.

1 Like

(sorry for off-topic)
@hadley, thanks for referring to this new (online) book. Great effort! It's actually the first time I heard about that.

1 Like