gpt4 book ai didi

r - 列表中表格的数据框

转载 作者:行者123 更新时间:2023-12-02 08:53:31 24 4
gpt4 key购买 nike

假设我有一个包含观察结果的列表:

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"

我想获取一个数据框,其中包含foo每个元素中vec每个元素的计数。我可以用 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。

最佳答案

一个解决方案(我的脑海中浮现出来):

# 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

关于r - 列表中表格的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6732926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com