如何在列表列表中对向量进行子集 [英] How to subset a vector inside list of list
本文介绍了如何在列表列表中对向量进行子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下列表列表:
foo <- list(a = list(x = 1:10, y = 11:25), b = list(x = 1:10, y = 100:110))
它看起来像这样:
> foo
$a
$a$x
[1] 1 2 3 4 5 6 7 8 9 10
$a$y
[1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
$b
$b$x
[1] 1 2 3 4 5 6 7 8 9 10
$b$y
[1] 100 101 102 103 104 105 106 107 108 109 110
我要做的是只选择产生收益的列表的前3个:
What I want to do is to only pick first 3 of the list yielding:
$a
$a$x
[1] 1 2 3
$a$y
[1] 11 12 13
$b
$b$x
[1] 1 2 3
$b$y
[1] 100 101 102
我该如何实现?
推荐答案
出现疯狂的?rapply
:
rapply(foo, f=head, n=3, how="list")
#$a
#$a$x
#[1] 1 2 3
#
#$a$y
#[1] 11 12 13
#
#
#$b
#$b$x
#[1] 1 2 3
#
#$b$y
#[1] 100 101 102
这是一个 r
递归 apply
,它将遍历每个列表,直到找到一个非列表,然后再应用 f =
unction. how ="list"
参数只是确保您再次获得相同的 list
结构.
This is a r
ecursive apply
which will go through each list until a non-list is found and then apply a f=
unction. The how="list"
argument just ensures that you get the same list
structure back again.
这篇关于如何在列表列表中对向量进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文