假设我有一个像这样的data.frame:
X1 X2 X3
1 A B A
2 A C B
3 B A B
4 A A C
我想计算每列中A,B,C等的出现次数,并将结果返回为
A_count B_count C_count
X1 3 1 0
X2 2 1 1
X3 1 2 1
我确定这个问题有一千个重复,但我似乎无法找到适合我的答案:(
运行
apply(mydata, 2, table)
我得到像
这样的东西$X1
B A
1 3
$X2
A C B
2 1 1
但它并不完全是我想要的,如果我尝试将其重新构建到数据框中,它就无法工作,因为我不会为每一行获得相同数量的列(比如上面没有C&#39的$ X1)。
我错过了什么?
非常感谢!
答案 0 :(得分:3)
您可以重构以包含每列共有的因子级别,然后制表。我还建议使用lapply()
代替apply()
,因为apply()
代表矩阵。
df <- read.table(text = "X1 X2 X3
1 A B A
2 A C B
3 B A B
4 A A C", h=T)
do.call(
rbind,
lapply(df, function(x) table(factor(x, levels=levels(unlist(df)))))
)
# A B C
# X1 3 1 0
# X2 2 1 1
# X3 1 2 1
答案 1 :(得分:3)
假设您的数据框为x
,我只会这样做:
do.call(rbind, tapply(unlist(x, use.names = FALSE),
rep(1:ncol(x), each = nrow(x)),
table))
# A B C
#1 3 1 0
#2 2 1 1
#3 1 2 1
<强>基准强>
# a function to generate toy data
# `k` factor levels
# `n` row
# `p` columns
datsim <- function(n, p, k) {
as.data.frame(replicate(p, sample(LETTERS[1:k], n, TRUE), simplify = FALSE),
col.names = paste0("X",1:p), stringsAsFactors = TRUE)
}
# try `n = 100`, `p = 500` and `k = 3`
x <- datsim(100, 500, 3)
## DirtySockSniffer's answer
system.time(do.call(rbind, lapply(x, function(u) table(factor(u, levels=levels(unlist(x)))))))
# user system elapsed
# 21.240 0.068 21.365
## my answer
system.time(do.call(rbind, tapply(unlist(x, use.names = FALSE), rep(1:ncol(x), each = nrow(x)), table)))
# user system elapsed
# 0.108 0.000 0.111
通过以下方式可以改善肮脏的答案:
## improved DirtySockSniffer's answer
system.time({clevels <- levels(unlist(x, use.names = FALSE));
do.call(rbind, lapply(x, function(u) table(factor(u, levels=clevels))))})
# user system elapsed
# 0.108 0.000 0.108
另请考虑user20650的回答:
## Let's try a large `n`, `p`, `k`
x <- datsim(200, 5000, 5)
system.time(t(table(stack(lapply(x, as.character)))))
# user system elapsed
# 0.592 0.052 0.646
虽然我的回答是:
system.time(do.call(rbind, tapply(unlist(x, use.names = FALSE), rep(1:ncol(x), each = nrow(x)), table)))
# user system elapsed
# 1.844 0.056 1.904
改进了Dirty的回答:
system.time({clevels <- levels(unlist(x, use.names = FALSE));
do.call(rbind, lapply(x, function(u) table(factor(u, levels=clevels))))})
# user system elapsed
# 1.240 0.012 1.263