Reputation: 23
I store my data in a multilevel nested list. This list may look like this
my.list = list()
my.list[[1]] = list("naive" = list("a"=c(1,1)) )
my.list[[2]] = list("naive" = list("b"=c(2,1)) )
my.list[[3]] = list("naive" = list("c"=c(3,1)) )
my.list[[4]] = list("naive" = list("d"=c(4,1)) )
my.list[[5]] = list("naive" = list("e"=c(5,1)) )
Now I want to do some operations on the stored values, like selecting the first elements of the 2-d vectors and combine them in another vector. Of course this can be done like the following
foo = c(my.list[[1]][["naive"]][[1]][1],
my.list[[2]][["naive"]][[1]][1],
my.list[[3]][["naive"]][[1]][1],
my.list[[4]][["naive"]][[1]][1],
my.list[[5]][["naive"]][[1]][1])
But this is really awkward if I have many more than 5 first level sublists. And I have the same feeling about for-looping through K
in my.list[[K]][["naive"]][[1]][1]
, K=1:5
.
The suggestions provided for similar questions using neat mapply
, Reduce
, sapply
cannot be applied directly due to presence of the "naive"
second level sublist.
Can someone help we with a clever and instructive solution, where values stored according to such multilevel list structure can be concatenated, added to each other or both? In example above, the final desired result could be adding respective components for all vectors, and storing the result in a new 2-d vector, that in this case would be foo = c(15,5)
. Your answer would help me a lot.
Upvotes: 2
Views: 1488
Reputation: 460
Yeah, sapply
will definitely do the trick for you in this situation:
sapply(my.list, function(x) x[["naive"]][[1]][1])
And you can generalize from here or sapply
/lapply
over the indices of the naive
vector if you need to.
Upvotes: 3