匯總/匯總每組的多個變量(例如總和,平均值)從數據幀,是否有聚集(一個簡單的方法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 關注
- 832 瀏覽
添加回答
舉報
0/150
提交
取消
