列表中的表的数据框

时间:2011-07-18 12:34:22

标签: r

假设我有一个包含观察结果的清单:

foo <- list(c("C", "E", "A", "F"), c("B", "D", "B", "A", "C"), c("B", 
"C", "C", "F", "A", "F"), c("D", "A", "A", "D", "D", "F", "B"
))

> foo
[[1]]
[1] "C" "E" "A" "F"

[[2]]
[1] "B" "D" "B" "A" "C"

[[3]]
[1] "B" "C" "C" "F" "A" "F"

[[4]]
[1] "D" "A" "A" "D" "D" "F" "B"

带有每个唯一元素的向量:

vec <- LETTERS[1:6]

> vec
[1] "A" "B" "C" "D" "E" "F"

我想获得一个数据框,其中包含vec每个元素中foo的每个元素的计数。我可以使用plyr以非常丑陋的未经实现的方式执行此操作:

> ldply(foo,function(x)sapply(vec,function(y)sum(y==x)))
  A B C D E F
1 1 0 1 0 1 1
2 1 2 1 1 0 0
3 1 1 2 0 0 2
4 2 1 0 3 0 1

但那显然很慢。怎么能更快地完成?我知道table(),但由于foo的某些元素中的0计数,我还没有真正弄清楚如何使用它。

2 个答案:

答案 0 :(得分:5)

一种解决方案(脱离我的头脑):

# convert foo to a list of factors
lfoo <- lapply(foo, factor, levels=LETTERS[1:6])
# apply table() to each list element
t(sapply(lfoo, table))
     A B C D E F
[1,] 1 0 1 0 1 1
[2,] 1 2 1 1 0 0
[3,] 1 1 2 0 0 2
[4,] 2 1 0 3 0 1

答案 1 :(得分:1)

或重塑:

cast(melt(foo), L1 ~ value, length)[-1]