3

I've a data frame corresponding to the sample below:

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

I would like to transform this data frame to a list object that could be conveniently implemented in selectInput:

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

I would like for the end-user to see the list of subjects in the selection and for the selectInput to return the corresponding numerical value (id).

If I attempt to get my list via:

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

The selectInput drop down menu shows all available options:

Select Input Preview

I'm only interested in listing subjects and passing the corresponding numerical values.

Konrad
  • 17,740
  • 16
  • 106
  • 167
  • I am not sure about the structure you want to get. Maybe `split(df$id, df$subject)`. –  Jul 03 '15 at 10:10

3 Answers3

7

Use function 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

Together with function with:

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

For the choices argument, you can use a named list, from the doc:

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

To make the named list you could try:

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

And in the app:

selectInput("subject", "Subject",
                choices = your_choices )
NicE
  • 21,165
  • 3
  • 51
  • 68
0

Use setNames, for example:

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

like in this example http://shiny.rstudio.com/gallery/option-groups-for-selectize-input.html

Igor Konoplyanko
  • 9,176
  • 6
  • 57
  • 100