Qaswed
Qaswed

Reputation: 3889

mutable naming list elements at initialization without eval(parse(paste()))

My question is similar to How to add variable key/value pair to list object?. I want to give a list element a mutable name according to the value of a variable. But I do not want to rename the list, but name it correctly right at initialization (I want a one liner) without using "The evil trio (eval, parse, paste)".

The "problem" of how list works is that

key <- "width" 
my_list <- list(key = 32) 

names the element (understandably) "key" and not "width", even if key <- "width" and one is eager to have the same result as my_list <- list(width = 32).

The "evil trio solution" would be my_list <- eval(parse(text = paste("list(", key, "=32)"))), but I am looking for a more elegant solution like list(eval(key) = 32) (which doesn't work).

Upvotes: 0

Views: 132

Answers (1)

Qaswed
Qaswed

Reputation: 3889

User docendo discimus gave the answer setNames(list(32), key) but "deleted [his] answer since it's already given in the Q&A linked in the question."

Unfortunately this nice answer there has (with my upvote) only 3 votes and is not straight forward to recognize as an suitable answer (as Assad Ebrahim talks about a "hash" and his code doesn't use the code from the OP).

Upvotes: 1

Related Questions