部署ごとの社員数を求めるとか
地域ごとの売上1位の店舗を求めるとか、グループ化して集計するという場面は多いので、
メモ。
これ(iris)↓から
SpeciesごとにSepal.Lengthが最大になる行だけを取り出したい。
つまり↓
とするには、
library(dplyr) iris %>% group_by(Species) %>% filter(Sepal.Length == max(Sepal.Length))
が、手っ取り早し。
標準のarrregate関数というものもあるが、対象列(Sepal.Length)のみの集計になってしまう。
aggregate(iris$Sepal.Length, list(iris$Species), max)
これを実行すると、
こうなって、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をキーに内部結合
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))
とする。