简体   繁体   中英

Creating a dynamic list with R to use it in shiny

I need to format a list so that the list items are displayed as radio buttons on my shiny application. Below is an example of how my list is currently formatted:

mylist = list("Choice 1"=1, "Choice 2"=2, "Choice 3"=3)

The list should be generated dynamically. The list will be queried to determine the correct name so as to replace "Choice 1", "Choice 2" and "Choice 3".

I have tried to use list<-append but it doesn't interpret the variable name. Example:

var = "SimpleTest"
mylist=list()
mylist<-append(mylist,list(var=1))

Current Output:

# $var
# [1] 1

My desired output is:

$SimpleTest
[1] 1

I edited your post to clarify the question and improve legibility.

If I understood you correctly, you are attempting to update the name (and only the name) of that list element, whose value is 1.

mylist = list("Choice 1"=1, "Choice 2"=2, "Choice 3"=3)
var = "SimpleTest"
mylist
# $`Choice 1`
# [1] 1
# $`Choice 2`
# [1] 2
# $`Choice 3`
# [1] 3

If so, the following code will do that. Assign the name of that list element which has the value 1, the string saved in variable var :

names(mylist)[which(mylist==1)]=var
mylist
# $SimpleTest
# [1] 1
# $`Choice 2`
# [1] 2
# $`Choice 3`
# [1] 3

I had exactly the same problem here how I solved it:

varnames <-c("Choice 1","Choice 2","Choice 3")
mylist<- setNames(as.list(seq(1,length(varnames))),varnames)
mylist
$`Choice 1`
[1] 1
$`Choice 2`
[1] 2
$`Choice 3`
[1] 3

Now you can update your selectInputs dynamically!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM