dplyr 패키지를 이용해 데이터의 하위 그룹 분석을 하려면 다음과 같은 코드를 사용할 수 있습니다.

library(dplyr)
iris %>%
  group_by(Species) %>%
  summarise(
    Sepal.Length_mean = mean(Sepal.Length),
    Sepal.Width_mean = mean(Sepal.Width)
  )
## # A tibble: 3 x 3
##   Species    Sepal.Length_mean Sepal.Width_mean
##   <fct>                  <dbl>            <dbl>
## 1 setosa                  5.01             3.43
## 2 versicolor              5.94             2.77
## 3 virginica               6.59             2.97

하위그룹에 대한 한두개 열의 값들만 궁금하다면 위와 같이 하면 문제가 없겠지만 분석을 하다보면 많은 열의 요약 평균 값이라던가 중위수 등을 본다던가, 그룹으로 묶인 데이터를 다음 단계로 전달하고 싶을 때가 생깁니다. 그럴 때는 summarise_all() 함수를 이용해 코드를 간단히 개선할 수 있습니다. 함수 안에 list()로 묶어 원하는 것들을 적용해 볼 수 있는데, colname_* 형식으로 column이 생성됩니다.

iris_summary <- iris %>%
  group_by(Species) %>%
  summarise_all(
    list(
      mean = mean,
      med = median,
      sd = sd
    )
  )

iris_summary
## # A tibble: 3 x 13
##   Species Sepal.Length_me… Sepal.Width_mean Petal.Length_me…
##   <fct>              <dbl>            <dbl>            <dbl>
## 1 setosa              5.01             3.43             1.46
## 2 versic…             5.94             2.77             4.26
## 3 virgin…             6.59             2.97             5.55
## # … with 9 more variables: Petal.Width_mean <dbl>, Sepal.Length_med <dbl>,
## #   Sepal.Width_med <dbl>, Petal.Length_med <dbl>, Petal.Width_med <dbl>,
## #   Sepal.Length_sd <dbl>, Sepal.Width_sd <dbl>, Petal.Length_sd <dbl>,
## #   Petal.Width_sd <dbl>

콘솔에서는 전체가 잘 안보여서 str()함수를 써 보도록 하겠습니다.

str(iris_summary)
## Classes 'tbl_df', 'tbl' and 'data.frame':    3 obs. of  13 variables:
##  $ Species          : Factor w/ 3 levels "setosa","versicolor",..: 1 2 3
##  $ Sepal.Length_mean: num  5.01 5.94 6.59
##  $ Sepal.Width_mean : num  3.43 2.77 2.97
##  $ Petal.Length_mean: num  1.46 4.26 5.55
##  $ Petal.Width_mean : num  0.246 1.326 2.026
##  $ Sepal.Length_med : num  5 5.9 6.5
##  $ Sepal.Width_med  : num  3.4 2.8 3
##  $ Petal.Length_med : num  1.5 4.35 5.55
##  $ Petal.Width_med  : num  0.2 1.3 2
##  $ Sepal.Length_sd  : num  0.352 0.516 0.636
##  $ Sepal.Width_sd   : num  0.379 0.314 0.322
##  $ Petal.Length_sd  : num  0.174 0.47 0.552
##  $ Petal.Width_sd   : num  0.105 0.198 0.275