我试图使用多个组对一个变量求和,但总是得到总和,尝试了dplyr,data.table和aggregate,但我总是得到总和,而不是组总和。
最后的努力是as.data.table
Totals06 <- as.data.table(testQ)[, sum(testQ$v23, na.rm=TRUE), by = .(testQ$v01, testQ$v05, testQ$v09)]
我做一些非常愚蠢的事情,感谢任何帮助。
答案 0 :(得分:0)
由于缺乏可重复的例子,这里有一个玩具示例:
df = data.frame(a=c("A","A","A","B","B","C","C","C"),species=c("cat","cat","dog","cat","dog","dog","horse","dog"),exp=c(1,2,3,4,5,3,2,1))
>df
# a species exp
#1 A cat 1
#2 A cat 2
#3 A dog 3
#4 B cat 4
#5 B dog 5
#6 C dog 3
#7 C horse 2
#8 C dog 1
使用dplyr
并按两个变量分组:
df%>%group_by(a,species)%>%summarise_at(.funs = sum,.vars = c("exp"))
# A tibble: 6 x 3
# Groups: a [?]
# a species exp
# <fctr> <fctr> <dbl>
#1 A cat 3
#2 A dog 3
#3 B cat 4
#4 B dog 5
#5 C dog 4
#6 C horse 2