简体   繁体   English

通过评估元素减少列表清单

[英]Reduce list of lists by evaluating elements

How do I reduce a list of lists to only contain the values that live up to a certain criteria? 如何减少列表列表,使其仅包含符合特定条件的值? I've seen similar questions, and looked at Filter , Reduce , etc. but can't seem to make anything work. 我见过类似的问题,并查看了FilterReduce等,但似乎无法使任何工作正常。

> h = list(A=c(1, 2, 3), B=c(2, 3, 4), C=c(0, 1, 2))
> h
$A
[1] 1 2 3

$B
[1] 2 3 4

$C
[1] 0 1 2 

Desired output: 所需的输出:

> MagicFunction(h, element >= 3)
$A
[1] 3

$B
[1] 3 4

You can try, 你可以试试,

Filter(length, lapply(h, function(i)i[i>=3]))

#$A
#[1] 3

#$B
#[1] 3 4

If you have elements with NA, then you can use na.omit to remove those, .ie 如果您的元素带有NA,则可以使用na.omit删除它们,即.ie

h = list(A=c(1, 2, 3), B=c(2, 3, 4), C=c(0, 1, 2), D=NA)
Filter(length, lapply(h, function(i)na.omit(i[i>=3])))

#$A
#[1] 3

#$B
#[1] 3 4

An alternative would be, 一个替代方案是

h = list(A=c(1, 2, 3), B=c(2, 3, 4), C=c(0, 1, 2), D=c(NA, 7))
Filter(length, lapply(h, function(i)(i[i >= 3 & !is.na(i)])))

#$A
#[1] 3

#$B
#[1] 3 4

#$D
#[1] 7

You can also do this with purrr and map . 您也可以使用purrrmap进行此purrr map applies the function across groups, then discard(is_empty) removes lists that contain no values (ie that were filtered out by the function). map跨组应用该函数,然后discard(is_empty)删除不包含任何值的列表(即该函数过滤掉的值)。 ~ is used to specify the function that is to be applied to each list and . ~用于指定要应用于每个列表和的功能. is a placeholder for each list passing through the function. 是通过函数传递的每个列表的占位符。

library(purrr)

map(h, ~.[. >= 3]) %>% discard(is_empty)

$A
[1] 3

$B
[1] 3 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM