Reputation: 7942
In R, I can add 1 to each element of a list by doing alist<-alist +1
. But what if I have something like alist<-list(list(1,2,3),list(2,3,4))
. Is there some way to add 1 to each element of the sublist without using a loop?
Upvotes: 1
Views: 798
Reputation: 37754
I just learned about this yesterday; it may be useful to others in similar situations; [[
allows for recursive indexing into lists, like this.
> alist[[c(1,2)]]
[1] 2
Upvotes: 5
Reputation: 28632
In the question list was written but the example showed a vector. I think the OP meant this:
alist <- list(list(1, 2, 3), list(2, 3, 4))
Instead of a loop you could use the recursive version of lapply
, see: ?rapply
.
> rapply(alist, function(x) x+1, how = "list" )
[[1]]
[[1]][[1]]
[1] 2
[[1]][[2]]
[1] 3
[[1]][[3]]
[1] 4
[[2]]
[[2]][[1]]
[1] 3
[[2]][[2]]
[1] 4
[[2]][[3]]
[1] 5
Upvotes: 8