每组聚合/汇总多个变量(即和,平均值等)

前端之家收集整理的这篇文章主要介绍了每组聚合/汇总多个变量(即和,平均值等)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从数据框架,有一个简单的方法来同时聚合(即求和)多个变量?

以下是一些示例数据:

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)

我想同时聚合来自df2数据框架的x1和x2变量按年和月。以下代码聚合x1变量,但是是否也可以同时聚合x2变量?

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

任何建议将不胜感激。

这个year()函数在哪里?

您还可以使用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
原文链接:https://www.f2er.com/javaschema/282913.html

猜你在找的设计模式相关文章