list 基于逻辑条件的列表中的子集元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6941506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:42:02  来源:igfitidea点击:

Subset elements in a list based on a logical condition

listrconditional

提问by jrara

How can I subset a list based on a condition (TRUE, FALSE) in another list? Please, see my example below:

如何根据另一个列表中的条件(TRUE、FALSE)对列表进行子集化?请看我下面的例子:

l <- list(a=c(1,2,3), b=c(4,5,6,5), c=c(3,4,5,6))
l
$a
[1] 1 2 3

$b
[1] 4 5 6 5

$c
[1] 3 4 5 6

cond <- lapply(l, function(x) length(x) > 3)
cond
$a
[1] FALSE

$b
[1] TRUE

$c
[1] TRUE

> l[cond]

Error in l[cond] : invalid subscript type 'list'

l[cond] 中的错误:无效的下标类型“列表”

采纳答案by James

[is expecting a vector, so use unliston cond:

[期待一个向量,所以使用unliston cond

l[unlist(cond)]
$b
[1] 4 5 6 5

$c
[1] 3 4 5 6

回答by Jason Morgan

This is what the Filterfunction was made for:

这是该Filter功能的用途:

Filter(function(x) length(x) > 3, l)
$b
[1] 4 5 6 5

$c
[1] 3 4 5 6

回答by PatrickR

Another way is to use sapplyinstead of lapply.

另一种方法是使用sapply代替lapply

cond <- sapply(l, function(x) length(x) > 3)
l[cond]

回答by NPE

> l[as.logical(cond)]
$b
[1] 4 5 6 5

$c
[1] 3 4 5 6

回答by jazzurro

I recently learned lengths(), which gets the length of each element of a list. This allows us to avoid making another list including logical values as the OP tried.

我最近学习了lengths(),它获取列表中每个元素的长度。这使我们能够避免在 OP 尝试时制作另一个包含逻辑值的列表。

lengths(l)
#a b c 
#3 4 4 

Using this in a logical condition, we can subset list elements in l.

在逻辑条件中使用它,我们可以在 中对列表元素进行子集化l

l[lengths(l) > 3]

$b
[1] 4 5 6 5

$c
[1] 3 4 5 6

回答by Andre Elrico

cond <- lapply(l, length) > 3
l[cond]