使用如下数据框
set.seed(100)
dfm <- data.frame(
id=sample(1:100, 6, replace = TRUE),
val1 = rep(c("true", "false"), 3),
val2=sample(c("true", "false"), 6, replace = TRUE))
id val1 val2
1 31 true false
2 26 false true
3 56 true false
4 6 false true
5 47 true false
6 49 false false
需要按id
汇总,以便结果每true
出现id
。所以我尝试以下
> aggregate(. ~ id, dfm, function(x) { length(x[x == "true"])})
id val1 val2
1 6 0 0
2 26 0 0
3 31 0 0
4 47 0 0
5 49 0 0
6 56 0 0
>
但是,这并没有为每列返回“true”的计数。
答案 0 :(得分:1)
我们可以使用rowsum
rowsum(+(dfm[-1]=="true"), dfm$id)
关于为什么OP的代码不起作用,这是因为factor
&#39; val&#39;列。使用stringsAsFactors=FALSE
创建&#39; dfm&#39; OP的代码应该可行。如果列为factor
,aggregate
将获得integer
存储模式,而不是&#39; true / false&#39;导致全部为0的值。
dfm <- data.frame(
id=sample(1:100, 6, replace = TRUE),
val1 = rep(c("true", "false"), 3),
val2=sample(c("true", "false"), 6, replace = TRUE), stringsAsFactors=FALSE)
aggregate(. ~ id, dfm, function(x) { length(x[x == "true"])})
# id val1 val2
#1 21 1 0
#2 29 1 1
#3 36 0 0
#4 40 0 0
#5 67 0 0
#6 77 1 0