通过变量中的共享值汇总行 [英] Aggregate rows by shared values in a variable

查看:57
本文介绍了通过变量中的共享值汇总行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有点愚蠢的R问题.如果我有一个矩阵(或数据框,以较容易使用的为准),如:

I have a somewhat dumb R question. If I have a matrix (or dataframe, whichever is easier to work with) like:

Year  Match
2008   1808
2008 137088
2008      1
2008  56846
2007   2704
2007 169876
2007  75750
2006   2639
2006 193990
2006      2

我想对这些年来的每个比赛计数求和(因此,例如2008行将是2008 195743,我将如何去做呢?我脑子里有几个解决方案,但是它们是所有这些都不必要地复杂,R倾向于将一些更简单的解决方案藏在某个地方.

And I wanted to sum each of the match counts for the years (so, e.g. the 2008 row would be 2008 195743, how would I go about doing this? I've got a few solutions in my head but they are all needlessly complicated and R tends to have some much easier solution tucked away somewhere.

您可以使用以下方法生成与上面相同的矩阵:

You can generate the same matrix above with:

structure(c(2008L, 2008L, 2008L, 2008L, 2007L, 2007L, 2007L, 
2006L, 2006L, 2006L, 1808L, 137088L, 1L, 56846L, 2704L, 169876L, 
75750L, 2639L, 193990L, 2L), .Dim = c(10L, 2L), .Dimnames = list(
NULL, c("Year", "Match")))

感谢您提供的任何帮助.

Thanks for any help you can offer.

推荐答案

aggregate(x = df$Match, by = list(df$Year), FUN = sum),假设df是上面的数据框.

aggregate(x = df$Match, by = list(df$Year), FUN = sum), assuming df is your data frame above.

这篇关于通过变量中的共享值汇总行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆