猿问

汇总/汇总每组的多个变量(例如总和,平均值)

汇总/汇总每组的多个变量(例如总和,平均值)

从数据帧,是否有聚集(一个简单的方法sum,mean,max同时等c)中多个变量?


以下是一些示例数据:


library(lubridate)

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)

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


### aggregate variables by year month

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

head(df2)

任何建议将不胜感激。


BIG阳
浏览 778回答 4
4回答

繁星淼淼

这个year()功能来自哪里?您还可以使用该reshape2包执行此任务:require(reshape2)df_melt <- melt(df1, id = c("date", "year", "month"))dcast(df_melt, year + month ~ variable, sum)#&nbsp; year month&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x21&nbsp; 2000&nbsp; &nbsp; &nbsp;1&nbsp; -80.83405 -224.95401592&nbsp; 2000&nbsp; &nbsp; &nbsp;2 -223.76331 -288.24180173&nbsp; 2000&nbsp; &nbsp; &nbsp;3 -188.83930 -481.56019134&nbsp; 2000&nbsp; &nbsp; &nbsp;4 -197.47797 -473.71374205&nbsp; 2000&nbsp; &nbsp; &nbsp;5 -259.07928 -372.4563522
随时随地看视频慕课网APP
我要回答