这是一份工作aggregate
:
d <- read.table(text="List Count
R472 1
R472 1
R472 2
R472 2
R845 1
R845 2
R845 2", header=TRUE)
aggregate(Count ~ List, data=d, FUN=table)
# List Count.1 Count.2
# 1 R472 2 2
# 2 R845 1 2
编辑:
上面的代码适用于您提供的情况,并且由于您已经接受了答案,我认为它也适用于您的较大情况,但是如果任何条目List
缺少Count
. 对于更一般的情况:
DF <- read.table(text="List Count
R472 1
R472 1
R472 2
R472 2
R845 1
R845 2
R845 2
R999 2", header=TRUE)
f <- function(x) {
absent <- setdiff(unique(DF$Count), x)
ab.count <- NULL
if (length(absent) > 0) {
ab.count <- rep(0, length(absent))
names(ab.count) <- absent
}
result <- c(table(x), ab.count)
result[order(names(result))]
}
aggregate(Count ~ List, data=d, FUN=f)
# List Count.1 Count.2
# 1 R472 2 2
# 2 R845 1 2
# 3 R999 0 1
编辑2:
刚刚看到@JasonMorgan 的回答。去接受那个。