Dynamically create selectInput ids based on vector length

I struggled to title this since I think it's more of a question about looping/lapply than a shiny question so any help clarifying would also be great!

I'm creating a Shiny app which requires certain divs to have the same dropdown menus, but I need to give each of the divs a unique id so I can access their input$id.

I've created a function to create the divs based on a vector of values, and when the value in the vector is ttest a selectInput should additionally be created.

But how do I make the ids of the select input ttest_1 , ttest_2 etc etc if I have multiple ttest values in the initial vector?

# create a vector with 2 ttest values
test <- c("ttest", "mean", "freq", "ttest")

library(shiny)

# create divs, either just print the name in the vector
# or if the name in the vector is "ttest" then make it a select input
aggBlocks <- function(data, name)
{
  div(style = "
      text-align: center;
      font-size: 12px;
      background-color: #A9A9A9;
      border-radius: 10px;
      color: black; margin-bottom: 5px;
      ",
      if (name == "ttest") {
        # how do I abstractly make the ids ttest_1 and ttest_2 
        # based on the occurances in the vector?
        selectInput(paste0("ttest"), "T-TEST", choices = c("Week 1", "Week 2", "Week 3"), selectize = FALSE)
      } else {
        name
      }
  )
}


ui <- fluidPage(
  div(lapply(test, aggBlocks, data = test)),
  verbatimTextOutput("debug")

)

server <- function(input, output) {

  output$debug <- renderPrint({
    # rather than just print input$ttest
    # need to print ttest_1, ttest_2 etc
    input$ttest
  })

}


shinyApp(ui = ui, server = server)

Any help appreciated!!

You can use input[[my_string_variable]] I think, just like with a list.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.