Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny - All sub-lists in "choices" must be named?

Tags:

r

shiny

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?

like image 228
Run Avatar asked May 04 '15 04:05

Run


2 Answers

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) 
like image 71
NicE Avatar answered Nov 20 '22 14:11

NicE


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)
like image 31
Peter Hill Avatar answered Nov 20 '22 13:11

Peter Hill