R筋

プログラミング、金融、育児

【R】グループ化して集計するあれこれ

部署ごとの社員数を求めるとか
地域ごとの売上1位の店舗を求めるとか、グループ化して集計するという場面は多いので、
メモ。

これ(iris)↓から
f:id:anpontan382:20190216105955p:plain
SpeciesごとにSepal.Lengthが最大になる行だけを取り出したい。
つまり↓
f:id:anpontan382:20190216110022p:plain
とするには、

library(dplyr)
iris %>% group_by(Species) %>% filter(Sepal.Length == max(Sepal.Length))

が、手っ取り早し。

標準のarrregate関数というものもあるが、対象列(Sepal.Length)のみの集計になってしまう。

aggregate(iris$Sepal.Length, list(iris$Species), max) 

これを実行すると、
f:id:anpontan382:20190216113118p:plain
こうなって、Sepal.Length以外は消えてしまう。
これをもとにもとの、irisと結合させれば同じことができる

A <- aggregate(iris$Sepal.Length, list(iris$Species), max) 
colnames(A) <- c("Species","Sepal.Length")
left_join(A , iris ,by=c("Sepal.Length","Species"))
#Sepal.LengthとSpeciesをキーに内部結合

f:id:anpontan382:20190216114223p:plain

tapplyでは、

tapply(iris$Sepal.Length,iris$Species,max)

によって、配列が返される

    setosa versicolor  virginica 
       5.8        7.0        7.9 

行ったり来たりで申し訳ないが、dplyrのsummariseでaggregateと同じ結果を求めるには

 iris %>% group_by(Species) %>% summarise(max(Sepal.Length))

とする。