How to count rows by group in R
· 1 min read · Updated March 14, 2026 · beginner
r count group-by dplyr data.table
Counting rows by group is a fundamental data manipulation task.
With dplyr
The tidyverse way uses count() or group_by() with tally():
library(dplyr)
# Simple count by group
counts <- df %>%
count(department)
# Count by multiple groups
counts <- df %>%
count(department, status)
# Count and sort
counts <- df %>%
count(department, sort = TRUE)
# Count with additional columns
counts <- df %>%
count(department, gender, wt = salary, name = "total_salary")
With base R
# Using table()
dept_counts <- table(df$department)
# Using by()
counts <- by(df$department, df$department, length)
# Using aggregate()
counts <- aggregate(rep(1, nrow(df)), by = list(department = df$department), sum)
With data.table
library(data.table)
dt <- as.data.table(df)
# Simple count by group
counts <- dt[, .N, by = department]
# Count by multiple groups
counts <- dt[, .N, by = .(department, status)]
# Count and sort
counts <- dt[, .N, by = department][order(-N)]
With table() for Frequency Tables
# Single variable
table(df$department)
# Two-way table
table(df$department, df$status)
# Proportions
prop.table(table(df$department))
Common Variations
| Task | dplyr | data.table |
|---|---|---|
| Count all | n() | .N |
| Weighted count | count(wt = x) | dt[, sum(x), by = group] |
| Count unique | n_distinct(x) | uniqueN(x) |
See Also
- group_by() — dplyr grouping
- count() — dplyr count function
- table() — Base R tabulation