rguides

How to Count Rows by Group in R with dplyr

When you count rows by group in R, the dplyr package offers count() as a direct shortcut, while base R’s table() handles simple cases without dependencies. Both approaches let you tally observations per category, and count() returns a tidy data frame that integrates cleanly with downstream summarisation and plotting steps.

library(dplyr)

# Count by single group
mpg |> count(class)

# Count by multiple groups and sort
mpg |> count(class, drv, sort = TRUE)

# Count and sort by descending frequency
mpg |> count(manufacturer, sort = TRUE)

count() is shorthand for group_by() followed by summarise(n = n()). Add sort = TRUE to return results in descending frequency order. For a quick one-column count without loading packages, table(df$col) does the job.

# Base R approach for quick counts
table(mpg$class)

Use add_count() to append the count as a new column instead of collapsing rows — helpful for filtering groups by size: df |> add_count(group) |> filter(n >= 5) keeps only groups with at least five observations. For weighted counts where each row contributes a fractional amount, pass wt = weight_column to count(). When working with data.tables, dt[, .N, by = group] provides the fastest equivalent and avoids loading dplyr entirely. The name argument in count() lets you customise the output column name instead of the default n.

See also