1

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?

6
  • 1
    You should provide a reproducible example ! what is modifyList ? Commented Jun 24, 2014 at 12:11
  • Ha that's just a base R function to modify an existing list Commented Jun 24, 2014 at 12:12
  • Sorry made into a full example now Commented Jun 24, 2014 at 12:15
  • No because that will rename the top level, whereas I want to rename sublist $varname to $c. Also I was just wondering if it could all be done in just one line, within the lapply statement. Commented Jun 24, 2014 at 12:19
  • Do you need to add variable c or rename existing (a,b) to c? Commented Jun 24, 2014 at 12:26

2 Answers 2

3
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Ha that's great - many thanks!! I finally hope to get my head around these kind of things :-)
1

I'm not able to comment on David Arenburg's comment above, however if you do this you can adjust it to have a vector of names.

m=list(list(a=1,b=2),list(a=1,b=2))
v=1:length(m)
varname=c('Var1','Var2')
names(m) <- rep(varname, length(m)/length(varname))

m now looks like this:

$Var1
$Var1$a
[1] 1

$Var1$b
[1] 2


$Var2
$Var2$a
[1] 1

$Var2$b
[1] 2

You can call the values in the list like you would a dataframe (with a $) like this:

m$Var1$a which will return 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.