DavideChicco.it
DavideChicco.it

Reputation: 3470

R, how to use the content of a variable as the name of a field of a list?

I'm working in and I would like to allocate a field having the name of the content of a variable. In the following example, I would like that a field of the list this_list was called bbb and had value 2, but I get several mistakes by using both paste() and eval(quote()):

var <- "bbb"

this_list <- list()
this_list$aaa <- 1

this_list$paste(var) <- 2
Error: attempt to apply non-function

this_list$eval(quote(var)) <- 2
Error: attempt to apply non-function

My desired output is:

str(this_list)
List of 2
 $ aaa: num 1
 $ bbb: num 2

Can someone help me and tell me the right command to use? Thanks!

Upvotes: 1

Views: 31

Answers (1)

akrun
akrun

Reputation: 887851

Instead of $, use [[ for evaluating the object

this_list[[var]] <- 2
this_list
#$aaa
#[1] 1

#$bbb
#[1] 2

Upvotes: 1

Related Questions