每组聚合/汇总多个变量(即和,平均值等) [英] Aggregate / summarize multiple variables per group (i.e. sum, mean, etc)

查看:448
本文介绍了每组聚合/汇总多个变量(即和,平均值等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是一些示例数据:

  days = 365 * 2 
date = seq(as.Date(2000-01-01),length = days,by = day)
year = year(date)
month = month(date)
x1 = cumsum(rnorm(days,0.05))
x2 = cumsum ,0.05))
df1 = data.frame(date,year,month,x1,x2)

我想同时从 df2 中汇总 x1 x2 / code>数据框按年和月。下面的代码聚合了 x1 变量,但也可以同时聚合 x2 变量?

  ###按月汇总的变量
df2 = aggregate(x1〜year + month,data = df1,sum,na。 rm = TRUE)
head(df2)

p>

解决方案

今年()函数在哪里?



使用reshape2包执行此任务:

  require(reshape2)
df_melt< - melt(df1,id = c(date,year,month))
dcast(df_melt,year + month〜variable,sum)
#year month x1 x2
1 2000 1 -80.83405 - 224.9540159
2 2000 2 -223.76331 -288.2418017
3 2000 3 -188.83930 -481.5601913
4 2000 4 -197.47797 -473.7137420
5 2000 5 -259.07928 -372.4563522


From a data frame, is there a easy way to aggregate (i.e. sum) multiple variables simultaneously?

Below are some sample data:

days = 365*2
date = seq(as.Date("2000-01-01"), length = days, by = "day")
year = year(date)
month = month(date)
x1 = cumsum(rnorm(days, 0.05)) 
x2 = cumsum(rnorm(days, 0.05))
df1 = data.frame(date, year, month, x1, x2)

I would like to simultaneously aggregate the x1 and x2 variables from the df2 data frame by year and month. The following code aggregates the x1 variable, but is it also possible to simultaneously aggregate the x2 variable?

### aggregate variables by year month
df2=aggregate(x1~year+month, data=df1, sum, na.rm=TRUE)
head(df2)

Any suggestions would be greatly appreciated.

解决方案

Where is this year() function from?

You could also use the reshape2 package for this task:

require(reshape2)
df_melt <- melt(df1, id = c("date", "year", "month"))
dcast(df_melt, year + month ~ variable, sum)
#  year month         x1           x2
1  2000     1  -80.83405 -224.9540159
2  2000     2 -223.76331 -288.2418017
3  2000     3 -188.83930 -481.5601913
4  2000     4 -197.47797 -473.7137420
5  2000     5 -259.07928 -372.4563522

这篇关于每组聚合/汇总多个变量(即和,平均值等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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