adding a field to each element of a list

Tag: r , list Author: felixvallen Date: 2014-01-25

I have a list

> (mylist <- list(list(a=1),list(a=2),list(a=3)))
[[1]]
[[1]]$a
[1] 1


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


[[3]]
[[3]]$a
[1] 3

and I want to add field b to each sublist from 11:13 to get something like

> (mylist <- list(list(a=1,b=11),list(a=2,b=12),list(a=3,b=13)))
[[1]]
[[1]]$a
[1] 1

[[1]]$b
[1] 11


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

[[2]]$b
[1] 12


[[3]]
[[3]]$a
[1] 3

[[3]]$b
[1] 13

How do I do this?

(note that I have a large number of such relatively small lists, so this will be called in apply and has to be reasonably fast).

lapply(mylist, function(l) {l$b <- l$a+10; l}) should work, so long as you're actually adding 10 to each a value...

Best Answer

mylist <- list(list(a=1),list(a=2),list(a=3))
b.vals <- 11:13
mylist <- lapply(
  1:length(mylist), 
  function(x) {
    mylist[[x]]$b <- b.vals[[x]]
    mylist[[x]]
} )

comments:

yep, this is what I came up with too, except for I use c(b=b.vals[x],mylist[[x]]) instead of <-. thanks!
@sds, your approach is a bit cleaner.