汇总/汇总每组的多个变量(例如总和,平均值)从数据帧,是否有聚集(一个简单的方法sum,mean,max同时等c)中多个变量?以下是一些示例数据:library(lubridate)days = 365*2date = 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)我想同时按年和月汇总数据框中的变量x1和x2变量df2。以下代码聚合x1变量,但是是否也可以同时聚合x2变量?### aggregate variables by year monthdf2=aggregate(x1 ~ year+month, data=df1, sum, na.rm=TRUE)head(df2)任何建议将不胜感激。
4 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
这个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
- 4 回答
- 0 关注
- 776 浏览
添加回答
举报
0/150
提交
取消