Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make list for shiny dropdown selectInput

Tags:

list

r

shiny

the shiny selectInput widget requires a named list of choices in this format:

choices = list(
  "mpg" = 1,
  "cyl" = 2,
  "disp" = 3,
  "hp" = 4
  # ..... etc
)

the data frames going to my shiny app will not have the same variable names, so I would like to generate the names list on the fly.

here is an attempt:

data(mtcars)

choices = data.frame(
  var = names(mtcars),
  num = 1:length(names(mtcars))
)

> head(choices)
   var num     mylist
1  mpg   1  "mpg" = 1
2  cyl   2  "cyl" = 2
3 disp   3 "disp" = 3
4   hp   4   "hp" = 4
5 drat   5 "drat" = 5
6   wt   6   "wt" = 6

paste(choices$mylist, collapse = ",")

this looks close but it does not work:

...
box(
        selectInput(
          "select",
          label = h3("Select box"),
          choices = list(
            paste(choices$mylist, collapse = ",")
          )
    )
...

enter image description here

how can i make this work?

like image 235
Henk Avatar asked Oct 13 '15 14:10

Henk


1 Answers

Hi if I understood your question right you could just do that :

data(mtcars)

choices = data.frame(
  var = names(mtcars),
  num = 1:length(names(mtcars))
)
# List of choices for selectInput
mylist <- as.list(choices$num)
# Name it
names(mylist) <- choices$var
# ui
ui <- fluidPage(
  selectInput(
    "select",
    label = h3("Select box"),
    choices = mylist
  )
)
# server
server <- function(input, output) {

}
# app
shinyApp(ui = ui, server = server)
like image 59
Victorp Avatar answered Nov 06 '22 23:11

Victorp