Generating selectInput choices from multiple factor columns in data frame

Does this do what you want?

library(shiny)

  df <- structure(list(A = structure(c(1L, 4L, 6L, 1L, 8L, 2L, 7L, 3L, 
                                       5L, 5L, 1L, 8L, 2L, 7L, 2L), 
                                     .Label = c("asd", "dfg", "fgdsgd", "fsd", "gdfgd", 
                                                "gs", "sdfg", "sf"), class = "factor"), 
                       B = c(29L, 24L, 46L, 50L, 43L, 29L, 32L, 24L, 35L, 39L, 33L, 47L, 53L, 26L,31L), 
                       C = structure(c(8L, 5L, 1L, 6L, 3L, 2L, 9L, 7L, 6L, 3L,  2L, 9L, 8L, 8L, 4L), 
                                     .Label = c("asd", "er", "fg", "gf", "gfd",  "gfg", "qw", "sf", "tr"), 
                                     class = "factor"), 
                       D = c(36L, 56L,39L, 26L, 56L, 35L, 27L, 31L, 33L, 45L, 34L, 27L, 43L, 40L, 56L), 
                       E = structure(c(8L, 5L, 1L, 6L, 3L, 2L, 9L, 7L, 6L, 3L, 2L,  9L, 8L, 8L, 4L), 
                                     .Label = c("asd", "er", "fg", "gf", "gfd", "gfg",  "qw", "sf", "tr"), 
                                     class = "factor"), 
                       F = c(44L, 34L, 37L, 23L, 37L, 51L, 28L, 36L, 33L, 31L, 39L, 43L, 25L, 37L, 43L)), 
                  class = "data.frame", row.names = c(NA, -15L))
  
  theNames <- names(Filter(is.factor,df))
  MyList  <- vector(mode = "list")
  
  for(i in theNames){
    MyList[[i]] <- levels(df[,i])
  }
  
  ui = fluidPage(
    selectInput("state", "Choose a state:", MyList),
    textOutput("result")
  )
  server = function(input, output) {
    output$result <- renderText({
      paste("You chose", input$state)
    })
  }

shinyApp(ui, server)
2 Likes