R:如何对按因子分组的列求和? [英] R: how to sum columns grouped by a factor?
本文介绍了R:如何对按因子分组的列求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的表:
user,v1,v2,v3
a,1,0,0
a,1,0,1
b,1,0,0
b,2,0,3
c,1,1,1
如何将其变成这个?
user,v1,v2,v3
a,2,0,1
b,3,0,3
c,1,1,1
推荐答案
您可以为此使用 dplyr
:
library(dplyr)
df = data.frame(
user = c("a", "a", "b", "b", "c"),
v1 = c(1, 1, 1, 2, 1),
v2 = c(0, 0, 0, 0, 1),
v3 = c(0, 1, 0, 3, 1))
group_by(df, user) %>%
summarize(v1_sum = sum(v1),
v2_sum = sum(v2),
v3_sum = sum(v3))
如果您不熟悉%>%
表示法,则基本上就像是bash的管道。它从 group_by()
中获取输出,并将其放入 summarize()
中。这样可以完成相同的事情:
If you're not familiar with the %>%
notation, it is basically like piping from bash. It takes the output from group_by()
and puts it into summarize()
. The same thing would be accomplished this way:
by_user = group_by(df, user)
df_summarized = summarize(by_user,
v1_sum = sum(v1),
v2_sum = sum(v2),
v3_sum = sum(v3))
这篇关于R:如何对按因子分组的列求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文