6.2 summarize()

What it does: collapses all rows and returns a one-row summary. R will recognize both the British and American spelling (summarise/summarize).

In the following example, summarize() allows us to calculate the mean price of all of the diamonds within our dataset.

diamonds %>% 
  summarize(avg.price = mean(price))
## # A tibble: 1 x 1
##   avg.price
##       <dbl>
## 1     3933.

Similar to mutate(), we can also perform multiple operations with summarize() and nest other useful functions inside it:

diamonds %>% 
  summarize(avg.price = mean(price),     # average price of all diamonds
            dbl.price = mean(price) * 2, # calculating double the average price
            random.add = 1 + 2,          # a math operation without an existing variable 
            avg.carat = mean(carat),     # average carat size of all diamonds
            stdev.price = sd(price))     # calculating the standard deviation 
## # A tibble: 1 x 5
##   avg.price dbl.price random.add avg.carat stdev.price
##       <dbl>     <dbl>      <dbl>     <dbl>       <dbl>
## 1     3933.     7866.          3     0.798       3989.