dplyr::count()
count(x, ..., wt = NULL, sort = FALSE, .drop = TRUE) Returns:
tibble · Updated March 13, 2026 · Tidyverse dplyr count tally summarise group-by
count() and tally() are dplyr verbs for counting observations. count() is a convenience wrapper that combines group_by() and summarise(n()) in one step. tally() adds a count column to a grouped tibble.
Syntax
count(x, ..., wt = NULL, sort = FALSE, .drop = TRUE)
tally(x, wt = NULL, sort = FALSE, name = "n")
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | tibble/data.frame | required | The data to count |
... | variables | optional | Variables to group by (count only) |
wt | variable | NULL | Optional weighting variable — adds a weighted count instead of raw count |
sort | logical | FALSE | If TRUE, sort output by count in descending order |
.drop | logical | TRUE | If FALSE, include combinations with zero counts |
name | string | "n" | Name of the count column (tally only) |
Examples
Basic usage
library(dplyr)
# Simple count of all rows
mtcars |> tally()
# # A tibble: 1 × 1
# n
# <int>
# 1 32
Count by group
# Count cars by number of cylinders
mtcars |> count(cyl)
# # A tibble: 3 × 2
# cyl n
# <dbl> <int>
# 1 4 11
# 2 6 7
# 3 8 14
Count by multiple groups
# Count by cylinders and gears
mtcars |> count(cyl, gear)
# # A tibble: 8 × 3
# cyl gear n
# <dbl> <dbl> <int>
# 1 4 3 1
# 2 4 4 7
# 3 4 5 3
# 4 6 3 2
# 5 6 4 4
# 6 6 5 1
# 7 8 3 5
# 8 8 5 9
Weighted counts
# Weight by horsepower - sum of hp per cylinder
mtcars |> count(cyl, wt = hp)
# # A tibble: 3 × 2
# cyl n
# <dbl> <dbl>
# 1 4 908
# 2 6 761
# 3 8 2929
Using tally() with existing groups
# First group, then tally
mtcars |> group_by(cyl) |> tally()
# # A tibble: 3 × 2
# cyl n
# <dbl> <int>
# 1 4 11
# 2 6 7
# 3 8 14
Sort by count
# Sort output in descending order
mtcars |> count(cyl, sort = TRUE)
# # A tibble: 3 × 2
# cyl n
# <dbl> <int>
# 1 8 14
# 2 4 11
# 3 6 7
Common Patterns
Proportions from counts
# Add a proportion column
mtcars |>
count(cyl) |>
mutate(prop = n / sum(n))
# # A tibble: 3 × 3
# cyl n prop
# <dbl> <int> <dbl>
# 1 4 11 0.344
# 2 6 7 0.219
# 3 8 14 0.438
Using with filter
# Find groups with more than N observations
mtcars |> count(cyl) |> filter(n > 10)
# # A tibble: 2 × 2
# cyl n
# <dbl> <int>
# 1 4 11
# 2 8 14
Naming the count column
# Custom name for the count column
mtcars |> count(cyl, name = "total_cars")
# # A tibble: 3 × 2
# cyl total_cars
# <dbl> <int>
# 1 4 11
# 2 6 7
# 3 8 14