Summarise Function in R


The summarise function in R returns one row for each combination of grouping variables. Note that summarise() and summarize() are synonyms. Summarise is part of dplyr.

library(tidyverse)
data <- mtcars
data %>% summarize(avg_mpg = mean(mpg))
data %>% summarize(avg_mpg = mean(mpg), 
                   median_mpg = median(mpg),
                   avg_weight = mean(wt))
# get the number of distinct cylinder configurations
data %>% summarize(unique_cyl = n_distinct(cyl))

Here is the output on the console of RStudio.

> library(tidyverse)
> data <- mtcars
> data %>% summarize(avg_mpg = mean(mpg))
   avg_mpg
1 20.09062
> data %>% summarize(avg_mpg = mean(mpg), 
+                    median_mpg = median(mpg),
+                    avg_weight = mean(wt))
   avg_mpg median_mpg avg_weight
1 20.09062       19.2    3.21725
> # get the number of distinct cylinder configurations
> data %>% summarize(unique_cyl = n_distinct(cyl))
  unique_cyl
1          3

Here is summarize_all.

> data %>% summarize_all(list(mean), na.rm = TRUE)
       mpg    cyl     disp       hp     drat      wt     qsec     vs      am   gear   carb
1 20.09062 6.1875 230.7219 146.6875 3.596563 3.21725 17.84875 0.4375 0.40625 3.6875 2.8125

Leave a Reply