subsetting all elements of a list by the same index values [duplicate]

喜你入骨 提交于 2021-02-05 11:19:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!