R aggregate函數

這個函數的功能比較強大,它首先將數據進行分組(按行),然後對每一組數據進行函數統計,最後把結果組合成一個比較nice的表格返回。根據數據對象不同它有三種用法,分別應用於數據框(data.frame)、公式(formula)和時間序列(ts):

  • aggregate(x, by, FUN, …, simplify = TRUE)
  • aggregate(formula, data, FUN, …, subset, na.action = na.omit)
  • aggregate(x, nfrequency = 1, FUN = sum, ndeltat = 1, ts.eps = getOption(“ts.eps”), …)

我們通過 mtcars 數據集的操作對這個函數進行簡單瞭解。mtcars 是不同類型汽車道路測試的數據框類型數據:

str(mtcars)

‘data.frame’: 32 obs. of 11 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 …
$ cyl : num 6 6 4 6 8 6 8 4 4 6 …
$ disp: num 160 160 108 258 360 …
$ hp : num 110 110 93 110 175 105 245 62 95 123 …
$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 …
$ wt : num 2.62 2.88 2.32 3.21 3.44 …
$ qsec: num 16.5 17 18.6 19.4 17 …
$ vs : num 0 0 1 1 0 1 0 1 1 1 …
$ am : num 1 1 1 0 0 0 0 0 0 0 …
$ gear: num 4 4 4 3 3 3 3 4 4 4 …
$ carb: num 4 4 1 1 2 1 4 2 2 4 …
先用attach函數把mtcars的列變量名稱加入到變量搜索範圍內,然後使用aggregate函數按cyl(汽缸數)進行分類計算平均值:

attach(mtcars)
aggregate(mtcars, by=list(cyl), FUN=mean)

Group.1 mpg cyl disp hp drat wt qsec vs am gear carb
1 4 26.66364 4 105.1364 82.63636 4.070909 2.285727 19.13727 0.9090909 0.7272727 4.090909 1.545455
2 6 19.74286 6 183.3143 122.28571 3.585714 3.117143 17.97714 0.5714286 0.4285714 3.857143 3.428571
3 8 15.10000 8 353.1000 209.21429 3.229286 3.999214 16.77214 0.0000000 0.1428571 3.285714 3.500000
by參數也可以包含多個類型的因子,得到的就是每個不同因子組合的統計結果:

 aggregate(mtcars, by=list(cyl, gear), FUN=mean)

Group.1 Group.2 mpg cyl disp hp drat wt qsec vs am gear carb
1 4 3 21.500 4 120.1000 97.0000 3.700000 2.465000 20.0100 1.0 0.00 3 1.000000
2 6 3 19.750 6 241.5000 107.5000 2.920000 3.337500 19.8300 1.0 0.00 3 1.000000
3 8 3 15.050 8 357.6167 194.1667 3.120833 4.104083 17.1425 0.0 0.00 3 3.083333
4 4 4 26.925 4 102.6250 76.0000 4.110000 2.378125 19.6125 1.0 0.75 4 1.500000
5 6 4 19.750 6 163.8000 116.5000 3.910000 3.093750 17.6700 0.5 0.50 4 4.000000
6 4 5 28.200 4 107.7000 102.0000 4.100000 1.826500 16.8000 0.5 1.00 5 2.000000
7 6 5 19.700 6 145.0000 175.0000 3.620000 2.770000 15.5000 0.0 1.00 5 6.000000
8 8 5 15.400 8 326.0000 299.5000 3.880000 3.370000 14.5500 0.0 1.00 5 6.000000
公式(formula)是一種特殊的R數據對象,在aggregate函數中使用公式參數可以對數據框的部分指標進行統計:

aggregate(cbind(mpg,hp) ~ cyl+gear, FUN=mean)

cyl gear mpg hp
1 4 3 21.500 97.0000
2 6 3 19.750 107.5000
3 8 3 15.050 194.1667
4 4 4 26.925 76.0000
5 6 4 19.750 116.5000
6 4 5 28.200 102.0000
7 6 5 19.700 175.0000
8 8 5 15.400 299.5000
上面的公式 cbind(mpg,hp) ~ cyl+gear 表示使用 cyl 和 gear 的因子組合對 cbind(mpg,hp) 數據進行操作。

aggregate在時間序列數據上的應用請參考R的函數說明文檔。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章