从一个数据框架,有一个简单的方法来聚合(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)