将数据框转换为 selectInput 中的选择列表(闪亮)

Transforming data frame to a selection list in selectInput (Shiny)

我有一个对应于以下示例的数据框:

df = data.frame(subject=c("Subject A", "Subject B", "Subject C", "Subject D"),id=c(1:4))

我想将此数据框转换为可以在 selectInput 中方便地实现的列表对象:

selectInput("subject", "Subject",
            choices = #my_new_list )

我希望最终用户看到选择中的主题列表,对于 selectInput 到 return 相应的数值(id).

如果我尝试通过以下方式获取列表:

df <- data.frame(lapply(df, as.character),
                         stringsAsFactors = FALSE)
df <- as.list(df)

selectInput 下拉菜单显示所有可用选项:

我只对列出主题并传递相应的数值感兴趣。

对于 choices 参数,您可以使用文档中的命名列表:

If elements of the list are named then that name rather than the value is displayed to the user

要创建命名列表,您可以尝试:

your_choices <- as.list(df$id)
names(your_choices) <- df$subject

在应用程序中:

selectInput("subject", "Subject",
                choices = your_choices )

使用函数split:

my_new_list <- split(df$id, df$subject)
my_new_list
#$`Subject A`
#[1] 1

#$`Subject B`
#[1] 2

#$`Subject C`
#[1] 3

#$`Subject D`
#[1] 4

连同函数with:

my_new_list <- with(df, split(id, subject))

使用setNames,例如:

selectizeInput('x3', 'X3', choices = setNames(state.abb, state.name))

就像这个例子http://shiny.rstudio.com/gallery/option-groups-for-selectize-input.html