Descriptive Statistics in R
A summary is an argument, not a fact
Descriptive statistics compress a column of numbers into a handful of claims: it is centred here, it spreads that far, it leans left. Those claims are chosen, not discovered. Mean versus median changes the headline, standard deviation versus interquartile range changes the verdict on volatility, and Pearson versus Spearman changes whether two columns look related at all. Reporting one number without naming which convention produced it is how two analysts get different answers from the same file.
This lesson treats the summary as something you specify deliberately. You will pick estimators that match the shape of your data, build tables that show what averages hide, and compute correlation with an explicit idea of what kind of relationship you are testing.
- Choose centre and spread estimators to match skew and outliers.
- Build frequency and cross-tabulation tables before modelling anything.
- Read correlation as association with a shape, never as cause.
Prerequisites
- !R vectors, data frames, and the pipe operator
- !Basic sampling and variable-type concepts
What You'll Learn
- 1Compute and interpret measures of centre and dispersion for skewed data
- 2Create frequency tables, proportions, and contingency tables
- 3Choose between Pearson, Spearman, and Kendall correlations
- 4Produce grouped summaries and a reusable column-profile report
Centre: three estimators, three different stories
The mean uses every observation, which makes it efficient when data really are symmetric and unstable when they are not. The median ignores magnitudes and cares only about order, so a single extreme value cannot drag it. The mode is the only one that works on categorical columns, and for numeric data it is usually a binning exercise rather than a lookup.
spend <- c(18, 22, 24, 25, 26, 27, 28, 30, 31, 33,
35, 36, 38, 40, 42, 45, 120, 145, 210, 380)
mean(spend) # dragged upward by three big accounts
mean(spend, trim = 0.10) # trimmed mean drops the extremes
median(spend) # the middle observation
stats::median(spend)
# Mode for categorical data: no built-in, so build one
get_mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
get_mode(c("monthly", "annual", "monthly", "trial", "monthly"))
weighted.mean(spend, w = seq_along(spend))
quantile(spend, probs = c(0.25, 0.5, 0.75))
quantile(spend, probs = seq(0, 1, by = 0.1), type = 7)
The gap between mean and median here is the message: with a right-skewed distribution of account values, the mean reports a typical spend that almost no account actually has. Trimmed means give you a compromise when you need a single figure that is still sensitive to the bulk of the data, and weighted means handle the common case where each row represents a different number of underlying customers.
| Estimator | Uses magnitudes | Robust to outliers | Works on categories | Typical use |
|---|---|---|---|---|
| Mean | yes | no | no | symmetric, untrimmed distributions |
| Trimmed mean | mostly | partly | no | skewed but not heavy-tailed data |
| Median | no | yes | no | income, latency, any heavy tail |
| Mode | no | yes | yes | plan tiers, categories, ratings |
| Weighted mean | yes | no | no | survey weights, per-customer rollups |
Dispersion: the part averages leave out
Two columns can share a mean and be completely different datasets. Dispersion is what separates them, and the choice of measure should follow the same logic as the choice of centre. Standard deviation squares deviations, so it reacts strongly to outliers; the interquartile range ignores everything outside the middle half; the median absolute deviation is the robust counterpart you reach for when data have both skew and tails.
x <- spend
range(x)
diff(range(x)) # full spread
var(x) # sample variance, denominator n - 1
sd(x) # square root of var()
IQR(x) # Q3 - Q1
mad(x) # median absolute deviation, robust
mad(x, constant = 1.4826) # consistent with sigma for normal data
cv <- function(v) sd(v) / mean(v) * 100
cv(x) # relative dispersion, unit-free
se <- function(v) sd(v) / sqrt(length(v))
se(x) # spread of the sample mean itself
fivenum(x) # Tukey five-number summary
summary(x) # min, Q1, median, mean, Q3, max
Notice that standard error is not a measure of spread in the data at all â it is the estimated spread of the sampling distribution of the mean, which shrinks as the square root of the sample size grows. Confusing the two produces the classic error of reporting a narrow standard error as evidence that the data are tightly clustered. The coefficient of variation is the right tool when you must compare dispersion between columns measured in different units, such as millimetres against kilograms.
Frequency tables: what the average hides
Counts and proportions are the first real diagnostic you should run on a categorical column, and cross-tabulations are how you see structure between two of them. R's table() family returns objects that behave like arrays, which means margins, proportions, and percentages are one function call away rather than a manual calculation.
plan <- c("monthly", "annual", "monthly", "trial", "annual",
"monthly", "monthly", "trial", "annual", "monthly")
region <- c("EMEA", "EMEA", "AMER", "AMER", "EMEA",
"APAC", "AMER", "APAC", "APAC", "EMEA")
counts <- table(plan)
counts
prop.table(counts)
round(prop.table(counts) * 100, 1)
# Contingency table with marginal totals
tab <- table(Region = region, Plan = plan)
addmargins(tab)
# Joint, row, and column percentages answer different questions
round(prop.table(tab) * 100, 1) # share of all customers
round(prop.table(tab, 1) * 100, 1) # plan mix within each region
round(prop.table(tab, 2) * 100, 1) # region mix within each plan
# Drop empty combinations that otherwise bloat the table
table(region, plan, useNA = "ifany")
Row percentages and column percentages are not interchangeable. Row percentages tell you the plan mix inside a region, which supports a localisation decision; column percentages tell you where a plan's customers come from, which supports a targeting decision. Reporting only the joint percentages of a large table tells you almost nothing, because every cell inherits the overall base rate.
Correlation: association with a shape
Correlation summarises how two columns move together, and the coefficient you compute is a statement about the kind of relationship you are willing to see. Pearson measures linear co-movement and is sensitive to scale and to outliers. Spearman correlates ranks, so it captures monotone relationships of any shape and tolerates heavy tails. Kendall's tau is based on concordant pairs, which makes it the most stable choice on small samples and the most interpretable when ties are frequent.
price <- c(10, 12, 14, 15, 18, 22, 25, 30, 35, 40)
sales <- c(30, 34, 38, 41, 45, 47, 52, 55, 60, 66)
rating <- c(5, 4, 5, 3, 4, 2, 3, 2, 1, 2)
cor(price, sales) # Pearson, default
cor(price, sales, method = "spearman") # rank-based
cor(price, sales, method = "kendall") # concordant pairs
cor(price, rating) # linear looks weak...
cor(price, rating, method = "spearman") # ...rank correlation is clear
cov(price, sales) # covariance: scale-dependent
cor(mtcars[, c("mpg", "wt", "hp", "disp")])
# Missing values must be handled explicitly, never silently
a <- c(1, 2, 3, NA, 5); b <- c(2, 4, 5, 8, 10)
cor(a, b) # returns NA
cor(a, b, use = "complete.obs") # pairwise deletion
cor(a, b, use = "pairwise.complete.obs")
cor.test(price, sales) # coefficient with a p-value
cor.test(price, sales, method = "spearman", exact = FALSE)
A correlation matrix is a starting point for finding columns worth plotting, not a verdict. Two columns can correlate at 0.9 because a third variable drives both, and a monotone but strongly curved relationship can produce a Pearson coefficient near zero while the Spearman coefficient sits above 0.9. Plot the pair whenever the coefficient surprises you.
Grouped summaries
Once the single-column estimators work, the useful question becomes how they differ across groups. tapply(), aggregate(), and dplyr::group_by() all answer it; they differ in how the result is shaped and how easily you chain further steps.
library(dplyr)
mtcars |>
as_tibble(rownames = "model") |>
group_by(cyl) |>
summarise(
n = n(),
mean_mpg = mean(mpg),
sd_mpg = sd(mpg),
median_mpg = median(mpg),
iqr_mpg = IQR(mpg),
.groups = "drop"
)
# Base equivalents
tapply(mtcars$mpg, mtcars$cyl, mean)
aggregate(mpg ~ cyl + am, data = mtcars,
FUN = function(v) c(mean = mean(v), sd = sd(v)))
# data.table for large grouped summaries
library(data.table)
dt <- as.data.table(mtcars)
dt[, .(mean_mpg = mean(mpg), sd_mpg = sd(mpg), n = .N), by = cyl]
Always carry the group size alongside the group mean. A mean computed on three observations and a mean computed on three hundred look identical in a bar chart, and the standard deviation of a group with a tiny sample is close to meaningless without its degrees of freedom.
A profile function for a new dataset
The fastest way to catch a bad column is to look at every column the same way, once, before any modelling. A small profile function turns that habit into a single call and surfaces type mismatches, missing values, and suspicious spreads immediately.
profile_columns <- function(df) {
rows <- lapply(names(df), function(nm) {
x <- df[[nm]]
base <- list(
column = nm,
type = class(x)[1],
n = length(x),
n_na = sum(is.na(x)),
pct_na = round(mean(is.na(x)) * 100, 2),
n_unique = length(unique(x))
)
if (is.numeric(x)) {
c(base, list(
mean = round(mean(x, na.rm = TRUE), 3),
sd = round(sd(x, na.rm = TRUE), 3),
cv = round(sd(x, na.rm = TRUE) / mean(x, na.rm = TRUE) * 100, 2),
min = min(x, na.rm = TRUE),
p50 = round(median(x, na.rm = TRUE), 3),
p99 = round(quantile(x, 0.99, na.rm = TRUE), 3),
max = max(x, na.rm = TRUE)
))
} else {
c(base, list(top = paste(head(names(sort(table(x), decreasing = TRUE)), 3),
collapse = ", ")))
}
})
bind_rows(rows)
}
profile_columns(mtcars)
Reading p99 against max is a quick outlier test, and cv above a few hundred percent usually means a column with a long tail or a unit error. The top column for character data does the same job that the mode does for categories: it tells you whether a column really has eight levels or eight thousand.
Mistakes that make summaries wrong
Common Mistakes
Reporting the mean for a strongly skewed column without the median
Fix: Show both; when mean and median differ substantially, the distribution is not symmetric and the mean is not typical.
Treating standard error as the spread of the data
Fix: Standard error describes the sampling distribution of a statistic; use sd() or IQR() for the data itself.
Computing cor() on data containing NA and accepting the NA result
Fix: Pass use = 'complete.obs' or handle missingness deliberately, and report how many rows were dropped.
Choosing Pearson by default for columns with outliers or nonlinear trends
Fix: Compare Pearson with Spearman; a large gap means the relationship is not linear or the tails dominate.
Averaging proportions or percentages across groups of different sizes
Fix: Aggregate the underlying counts first, then divide by the pooled total.
Publishing a cross-tabulation as joint percentages only
Fix: State the margin you used â row, column, or total â because each answers a different question.
Calling get_mode() results meaningful for continuous measurements
Fix: Bin continuous data into meaningful intervals first, or report quantiles instead of a mode.
Practices that keep summaries honest
Best Practices
- Always report the sample size next to any summary statistic.
- Pair each centre measure with a dispersion measure from the same family.
- Check missingness per column before computing anything that assumes completeness.
- Use quantiles and five-number summaries to see shape before choosing estimators.
- Standardise units when comparing dispersion across columns, or use the coefficient of variation.
- Profile every column of a new dataset with one function before trusting a single model.
- Keep summary functions pure and side-effect free so they compose into reports.
Key takeaways
Key Takeaways
- The mean is efficient under symmetry and misleading under skew; the median is the robust default for heavy-tailed columns.
- Dispersion choices mirror centre choices: standard deviation with the mean, interquartile range with the median.
- Standard error describes uncertainty in a statistic, not variability in the data.
- table(), prop.table(), and addmargins() cover counts, joint shares, and row or column shares in one family.
- Pearson measures linear association, Spearman measures monotone association, and the gap between them is diagnostic.
- Correlation never establishes causation; plot any pair whose coefficient you did not expect.
- Grouped summaries must carry their group sizes, and every dataset deserves one column-profile pass before analysis.
Where to go next
- R Probability Distributions â the distributions your summaries implicitly assume.
- R Hypothesis Testing â turning descriptive gaps into formal statements.
- R Linear Regression â modelling the relationships correlation only hints at.