用相同的索引值对列表的所有元素进行子设置 [英] subsetting all elements of a list by the same index values
本文介绍了用相同的索引值对列表的所有元素进行子设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能微不足道,但是我没有找到解决方案.我正在尝试通过相同的索引值对列表的所有元素进行子集化.
Probably trivial, but I didn't find a solution. I am trying to subset all elements of a list by the same index values.
假设我的清单是: mylist = list(seq(22,30,2),c(1:5),rep(8,5))
这给了我
[[1]]
[1] 22 24 26 28 30
[[2]]
[1] 1 2 3 4 5
[[3]]
[1] 8 8 8 8 8
我试图只提取值 [2:4] 并删除元素的其他值,所以我得到一个看起来像
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
我尝试过foreach的组合
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
我要去哪里错了?
推荐答案
存入@Richard Scriven
credit to @Richard Scriven
解决方案:
lapply(mylist, "[", 2:4)
这篇关于用相同的索引值对列表的所有元素进行子设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文