制作闪亮下拉列表selectInput的列表

时间:2015-10-13 14:15:22

标签: r list shiny

闪亮的selectInput小部件需要以这种格式命名的选择列表:

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

进入我的闪亮应用程序的数据框将没有相同的变量名称,因此我想动态生成名称列表。

这是一次尝试:

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 = ",")

这看起来很接近但不起作用:

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

enter image description here

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:6)

如果我理解你的问题,你可以这样做:

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)