Shiny - All sub-lists in “choices” must be named?

2020-08-23 04:32发布

问题:

I want to create a select options like this below,

<select id="species">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

So I use data frame to create a table that stores the data,

# Create the species table for select input.
title <- c('A', 'B', 'C')
code <- c('1', '2', '3')
species <- data.frame(title, code)

# Set choices of title and code for select input.
choicesSpecies <- setNames(species$code, species$title)

Shiny's ui.R,

selectInput(inputId = "species",
                  label = "Species:",
                  choices = choicesSpecies),

I get this error,

Error in (function (choice, name)  : 
  All sub-lists in "choices" must be named.

What does it mean? How can I fix it to get the result that I need?

回答1:

Having the code column as a factor in your data frame seems to be the issue, maybe try:

choicesSpecies <- setNames(as.numeric(species$code), species$title)

Or:

#create the named list
title <- c('A', 'B', 'C')
code <- c('1', '2', '3')
names(code) <- title

In your ui.R:

selectInput(inputId = "species",
                label = "Species:",
                choices = code) 


回答2:

In response to your comment (not enough rep to reply) regarding:

code <- c('a','b','c')

You need to change them to characters in the same way you were changing them to numeric. e.g.

choicesSpecies <- setNames(as.character(species$code), species$title)


标签: r shiny