Create one or more scalar variables summarizing the variables of an existing tbl. Tbls with groups created by group_by() will result in one row in the output for each group. Tbls with no groups will result in one row.

summarise(.data, ...)

summarize(.data, ...)

Arguments

.data

A tbl. All main verbs are S3 generics and provide methods for tbl_df(), dtplyr::tbl_dt() and dbplyr::tbl_dbi().

...

Name-value pairs of summary functions. The name will be the name of the variable in the result. The value should be an expression that returns a single value like min(x), n(), or sum(is.na(y)).

The arguments in ... are automatically quoted and evaluated in the context of the data frame. They support unquoting and splicing. See vignette("programming") for an introduction to these concepts.

Value

An object of the same class as .data. One grouping level will be dropped.

Details

summarise() and summarize() are synonyms.

Useful functions

Backend variations

Data frames are the only backend that supports creating a variable and using it in the same summary. See examples for more details.

Tidy data

When applied to a data frame, row names are silently dropped. To preserve, convert to an explicit variable with tibble::rownames_to_column().

See also

Other single table verbs: arrange, filter, mutate, select, slice

Examples

# A summary applied to ungrouped tbl returns a single row mtcars %>% summarise(mean = mean(disp), n = n())
#> mean n #> 1 230.7219 32
# Usually, you'll want to group first mtcars %>% group_by(cyl) %>% summarise(mean = mean(disp), n = n())
#> # A tibble: 3 x 3 #> cyl mean n #> <dbl> <dbl> <int> #> 1 4 105. 11 #> 2 6 183. 7 #> 3 8 353. 14
# Each summary call removes one grouping level (since that group # is now just a single row) mtcars %>% group_by(cyl, vs) %>% summarise(cyl_n = n()) %>% group_vars()
#> [1] "cyl"
# Note that with data frames, newly created summaries immediately # overwrite existing variables mtcars %>% group_by(cyl) %>% summarise(disp = mean(disp), sd = sd(disp))
#> # A tibble: 3 x 3 #> cyl disp sd #> <dbl> <dbl> <dbl> #> 1 4 105. NA #> 2 6 183. NA #> 3 8 353. NA
# Refer to column names stored as strings with the `.data` pronoun: var <- "mass" summarise(starwars, avg = mean(.data[[var]], na.rm = TRUE))
#> # A tibble: 1 x 1 #> avg #> <dbl> #> 1 97.3
# For more complex cases, knowledge of tidy evaluation and the # unquote operator `!!` is required. See https://tidyeval.tidyverse.org/ # # One useful and simple tidy eval technique is to use `!!` to # bypass the data frame and its columns. Here is how to divide the # column `mass` by an object of the same name: mass <- 100 summarise(starwars, avg = mean(mass / !!mass, na.rm = TRUE))
#> # A tibble: 1 x 1 #> avg #> <dbl> #> 1 0.973