假设我有一个清单
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