问题
Probably trivial, but I didn't find a solution. I am trying to subset all elements of a list by the same index values.
Assuming my list is:
mylist = list( seq(22,30,2), c(1:5), rep(8,5))
which gives me
[[1]]
[1] 22 24 26 28 30
[[2]]
[1] 1 2 3 4 5
[[3]]
[1] 8 8 8 8 8
I am trying to extract only the values [2:4] and drop the other values of the element, so i get a list that looks like
[[1]]
[1] 24 26 28
[[2]]
[1] 2 3 4
[[3]]
[1] 8 8 8
I have tried a combination of foreach an lapply
sub = foreach(i = c(1:3)) %do% {
lapply(mylist, function(x){mylist[[i]][c(2:4)]})
}
However I end up with a threefold replication
[[1]]
[[1]][[1]]
[1] 24 26 28
[[1]][[2]]
[1] 24 26 28
[[1]][[3]]
[1] 24 26 28
[[2]]
[[2]][[1]]
[1] 2 3 4
[[2]][[2]]
[1] 2 3 4
[[2]][[3]]
[1] 2 3 4
[[3]]
[[3]][[1]]
[1] 8 8 8
[[3]][[2]]
[1] 8 8 8
[[3]][[3]]
[1] 8 8 8
Where am I going wrong?
回答1:
credit to @Richard Scriven
solution:
lapply(mylist, "[", 2:4)
来源:https://stackoverflow.com/questions/32209527/subsetting-all-elements-of-a-list-by-the-same-index-values