0

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).

Community
  • 1
  • 1
Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • I deleted my answer since it's already [given in the Q&A](http://stackoverflow.com/a/31298923/3521006) linked in the question. IMO, it's the best option – talat Jul 20 '16 at 15:40
  • @docendodiscimus In general I agree with you, but unfortunately this nice answer 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). So feel free to post your answer again (I'll delete my own answer then of course). – Qaswed Jul 20 '16 at 15:55

1 Answers1

1

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).

Community
  • 1
  • 1
Qaswed
  • 3,649
  • 7
  • 27
  • 47