根据R中的属性过滤列表对象

时间:2017-05-18 12:56:31

标签: r list filter subset

我想构建一个对象列表并根据它们的一个属性提取对象。例如

persons_list <- list(PersonA = list(color = 'red', group = 1),
                     PersonsB = list(color = 'blue', group = 1),
                     PersonsC = list(color = 'green', group = 2))

现在我想将所有颜色提取为一个向量,其中group等于1,结果为:

c('red', 'blue')

我不确定列表是否可以到达此处,但我之所以选择它是因为我还希望能够通过键入

来使用列表的自动完成/浏览功能
persons_list$PersonA

5 个答案:

答案 0 :(得分:1)

我们可以做到

unlist(lapply(persons_list, function(x) x$color[x$group==1]), use.names = FALSE)
#[1] "red"  "blue"

答案 1 :(得分:1)

不,这个数据结构对于您的用例来说并不是最理想的。使用data.frame:

persons <- data.frame(person = c("A", "B", "C"),
                      color = c("red", "blue", "green"),
                      group = c(1, 1, 2),
                      stringsAsFactors = FALSE)
persons[persons$group == 1, "color"]
#[1] "red"  "blue"

表格结构不仅更自然,查找也更有效。

答案 2 :(得分:1)

Akrun总是更快。 : - )

更一般。您可以构建一些通用功能来完成这项工作而无需太多的认知努力。我还没有构建任何工具来从列表中选择东西。但我可以放弃

remove_if <- function(lst,test_fn) {
    ## DD . char or list
    if (class(lst)=="character"){
        unlist(lapply(lst ,function(x){if(!(test_fn(x))) x }))
    } else {

       remove_if_null(lapply(lst ,function(x){if(!(test_fn(x))) x }))}
    }

删除第2组,然后选择所需的部分。

unlist(lapply(remove_if(persons_list, function(x) x$group==2),"[[",1))

## PersonA PersonsB 
##   "red"   "blue" 

答案 3 :(得分:0)

library(rlist)有很多很好的列表功能,可以将一些整齐的动词用于列出操作。

library(rlist)
library(magrittr)

list.filter(persons_list, group == 1) %>%
    list.select(color) %>%
    unlist(use.names = F)

答案 4 :(得分:0)

我知道这是旧的,但我错过了更一般的答案。

我会使用:

unlist(lapply(persons_list[which(sapply(persons_list, function(person) { person$group==1 }))], function(x) x$color), use.name = FALSE)

或者为了更容易阅读,我可能会把它分成两行:

第一个过滤器

persons_in_group_1 = persons_list[which(sapply(persons_list, function(person) { person$group==1 }))]

然后映射所需的属性:

unlist(lapply(persons_in_group_1, function(x) x$color ), use.names = FALSE)
相关问题