データフレームから、複数の変数を同時に集計 ( sum
、mean
など)する簡単な方法はありますか?max
以下にサンプルデータを示します。
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)
ベストアンサー1
はい、 では、集計する数値変数を指定formula
できます。cbind
aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
year month x1 x2
1 2000 1 7.862002 -7.469298
2 2001 1 276.758209 474.384252
3 2000 2 13.122369 -128.122613
...
23 2000 12 63.436507 449.794454
24 2001 12 999.472226 922.726589
?aggregate
、formula
議論、および例を参照してください。