SEHOCKETT SEHOCKETT - 3 months ago 26
R Question

R Shiny: Using a Vector for Display and another Vector for Value in Choice List

I'm curious if there is a way to use a vector as the display value and another vector as the actual value, or name, in a choice list without having to explicitly declare each value.

Here's a simple example:

# vect1 is the vector I would like as the display list
vect1 <- c("A", "B", "C", "D", "E")

# vect2 is the vector I would like as the name group

vect2 <- c("01", "02", "03", "04", "05")

# To get the desired output, this is how I would create a selectInput widget on the
# ui side to get the desired outcome.
choices = list("A" = "01",
"B" = "02",
"C" = "03",
"D" = "04",
"E" = "05"))

# Instead, I would like to do something like the following to create the same output:
selectInput("exampleinput", choices = list(vect1 = vect2))

I'm not sure if this is even possible, but it would be very handy and clean. The application is that I have codes for different states that will be meaningless to the users of the app. For me, the codes are necessary to load in data. The vectors that I'm actually using are created dynamically. My app is working perfectly fine, and I am aware that I could easily write a function to convert the state abbreviations that I would like to be displayed to the state codes I will use behind the scenes; It would just be so much cleaner and easier if something like the above is possible.

Thank you, in advance, for all of the help!


You can use setNames like this:

choices = setNames(vect2,vect1)
selectInput("exampleinput","exampleinput", choices = choices)