Search code examples
rlist-manipulation

R: name list element by variable


Probably been asked before and I've seen some similar questions, but I would like to name my list elements according to the name of a variable varname in the statements

m=list(list(a=1,b=2),list(a=1,b=2))
v=1:length(m)
varname="c"
m=lapply(1:length(m), function(i) modifyList(m[[i]],list(varname=v[[i]])))

where m is a nested list and v a vector of the same length.

Problem is this returns me with sublists that are named varname as opposed to "c":

m
[[1]]
[[1]]$a
[1] 1

[[1]]$b
[1] 2

[[1]]$varname
[1] 1


[[2]]
[[2]]$a
[1] 1

[[2]]$b
[1] 2

[[2]]$varname
[1] 2

Probably quite trivial, but how should I solve this?


Solution

  • m=list(list(a=1,b=2),list(a=1,b=2))
    v=1:length(m)
    varname="c"
    

    This will work:

    m2=lapply(1:length(m), 
         function(i) modifyList(m[[i]],setNames(list(v[[i]]),varname)))
    

    or

    m2=mapply(function(x,y) {x[[varname]] <- y; x},m,v,SIMPLIFY=FALSE)