条件选择R列表对象内的表中的项

时间:2012-01-28 19:46:53

标签: r list

我有一个包含一系列表的R列表。列表中的每个表都包含命名项及其对应的值。我想迭代列表中的每个表,并返回每个表中有多少项具有value == 1的计数。

例如,假设以下列表:

> someitems <- c("the", "cat", "and", "the", "hat")
> someotheritems <- c("it", "was", "the", "best", "of", "times", "it", "was", "the")
> my.list <- list(table(someitems), table(someotheritems))
> my.list

[[1]]
someitems
and cat hat the 
  1   1   1   2 

[[2]]
someotheritems
 best    it    of   the times   was 
    1     2     1     2     1     2 

我现在需要返回列表中每个具有value == 1

的表中的项目计数

e.g。从以上回归

3
3

我可以看到,如何通过循环来做到这一点,但如何在没有循环的情况下做到这一点?

我已使用lapply()进行过实验,我知道如何使用以下方法获取值:

lapply(my.list, '[')

我编写了一个用于检测items == 1的自定义函数。例如

is.one <- function(x) if(x==1) return (TRUE) else return(FALSE)

但是我并没有完全理解如何将两者结合起来,而且应该比使用这种愚蠢的功能更容易。

谢谢!

2 个答案:

答案 0 :(得分:1)

在学习如何执行此操作时,使用单个实例然后在匿名函数上使用lapply会有所帮助:

> my.list[[1]] == 1
someitems
  and   cat   hat   the 
 TRUE  TRUE  TRUE FALSE 
> sum(my.list[[1]] == 1)
[1] 3
> lapply(my.list, function(x) sum(x == 1)  )
[[1]]
[1] 3

[[2]]
[1] 3

如果您希望结果是常规的,那么sapply有时可以将返回值减少为向量或矩阵:

sapply(my.list, function(x) sum(x == 1) )
[1] 3 3

答案 1 :(得分:1)

library(plyr) 
count=ldply(my.list, function(x) length(which(x==1)))