Day 9 of 30·Data Manipulation
Summarizing: group_by() + summarise() vs. PROC MEANS
Aggregate statistics by group without leaving your data pipeline.
Learning objectives
- 1Compute grouped statistics with group_by() + summarise().
- 2Replace PROC MEANS / PROC SUMMARY output datasets.
- 3Count records with n() and n_distinct().
- 4Produce tidy summary tables ready for reporting.
Key SAS® → R comparison
| Task | SAS® | R |
|---|---|---|
| Group means | proc means; class arm; var age; | group_by(arm) |> summarise(mean(age)) |
| N per group | proc freq; tables arm; | count(df, arm) |
| Distinct count | nlevels / distinct | n_distinct(usubjid) |
| Multiple stats | output out= mean= std=; | summarise(m=mean(x), s=sd(x)) |
Code examples
SAS®
proc means data=adsl n mean std;
class arm; var age;
output out=stats;
run;R
stats <- adsl |>
group_by(arm) |>
summarise(
n = n(),
mean = mean(age, na.rm = TRUE),
sd = sd(age, na.rm = TRUE)
)Note: summarise() returns a tidy tibble — one row per group — that drops straight into a reporting table.
Explanation
group_by() declares the grouping and summarise() collapses each group to a single row of statistics, replacing PROC MEANS/SUMMARY output datasets with a structure that is already tidy.
Because the result is just another tibble, you can immediately pivot, join, or format it — no intermediate OUTPUT OUT= dataset wrangling required.
Practice exercise
Produce a table of N, mean, SD, min and max age by treatment arm, plus the number of distinct subjects per arm.