列表中的向量频率
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列表中的向量频率相关的知识,希望对你有一定的参考价值。
假设我有一个清单
test <- list(c(1, 2, 3), c(2, 4, 6), c(1, 5, 10), c(1, 2, 3), c(1, 5, 10), c(1, 2, 3))
我需要计算所有这些向量,以便所需的输出应如下所示:
Category Count
1, 2, 3 3
2, 4, 6 1
1, 5, 10 2
在R中有什么简单的方法如何实现这一目标?
答案
你可以粘贴并使用table
,即
as.data.frame(table(sapply(test, paste, collapse = ' ')))
这使,
Var1 Freq 1 1 2 3 3 2 1 5 10 2 3 2 4 6 1
另一答案
函数unique()
可以在列表中工作。为了计数,可以使用identical()
:
test <- list(c(1, 2, 3), c(2, 4, 6), c(1, 5, 10), c(1, 2, 3), c(1, 5, 10), c(1, 2, 3))
Lcount <- function(xx, L) sum(sapply(L, identical, y=xx))
sapply(unique(test), FUN=Lcount, L=test)
unique(test)
结果为data.frame:
result <- data.frame(
Set=sapply(unique(test), FUN=paste0, collapse=','),
count= sapply(unique(test), FUN=Lcount, L=test)
)
result
# > result
# Set count
# 1 1,2,3 3
# 2 2,4,6 1
# 3 1,5,10 2
以上是关于列表中的向量频率的主要内容,如果未能解决你的问题,请参考以下文章
片段 A 的列表视图中的片段 B 中的新列表视图,单击 A 的列表项