グループごとに複数の変数を集計/要約する(例:合計、平均) 質問する

グループごとに複数の変数を集計/要約する(例:合計、平均) 質問する

データフレームから、複数の変数を同時に集計 ( summeanなど)する簡単な方法はありますか?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および変数を年と月ごとに同時に集計したいと思います。次のコードは 変数を集計しますが、 変数を同時に集計することもできますか?x2df2x1x2

### 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

?aggregateformula議論、および例を参照してください。

おすすめ記事