Back to Blog
Guidesstatisticsdata-analysismean-median-mode

Descriptive Statistics, From Mean to Quartiles

Mean, median, mode, variance, standard deviation, quartiles and IQR, worked through with real numbers, including why calculators disagree on sample variance and quartile methods.

LoopalooPublished May 1, 202611 min read

Descriptive statistics is the part of statistics that does not try to predict anything. It just tells you what a pile of numbers looks like: where the middle is, how spread out the values are, and whether anything is sitting way out in the tail. It is the first thing you run on a new dataset, and it is the layer most people get subtly wrong, usually because two reasonable definitions disagree and nobody mentions which one the tool picked.

This post walks through the core measures (mean, median, mode, variance, standard deviation, range, quartiles, IQR) with worked numbers. It also pins down the two places where software really does diverge: whether variance divides by n or n-1, and how quartiles get located in a sorted list. Both choices change the output, and both are easy to make silently.

The running dataset for most examples is ten values with a couple of repeats and nothing exotic: 12, 15, 18, 21, 24, 27, 30, 15, 18, 21.

The three "averages" and when each one lies

"Average" is ambiguous. There are three common centers, and they answer different questions.

The mean is the sum divided by the count. For our ten numbers the sum is 201, so the mean is 201 / 10 = 20.1. In code this is exactly what you would expect:

const sum = values.reduce((total, x) => total + x, 0);
const mean = sum / values.length;

The mean uses every value, which is its strength and its weakness. One huge outlier drags it. If you append a single 300 to the set, the mean jumps from 20.1 to about 45.5 even though ten of the eleven numbers are 30 or less. That is the mean "lying": it reports a center that no actual data point is near.

The median is the middle value once the data is sorted. With an even count there is no single middle, so you average the two middle values. Sorted, our set is 12, 15, 15, 18, 18, 21, 21, 24, 27, 30. With ten elements the two middle slots are index 4 and index 5 (zero-based), holding 18 and 21, so the median is 19.5:

const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
const median = sorted.length % 2 === 0
  ? (sorted[mid - 1] + sorted[mid]) / 2
  : sorted[mid];

The comparator in that sort is not optional. JavaScript's default sort() compares elements as strings, so [10, 9, 1].sort() returns [1, 10, 9], and every order-based statistic built on top of it comes out wrong.

The median ignores how extreme the extremes are; it only cares about ordering. Append that 300 and the median barely moves (to 21). That robustness is why income, home prices, and response-time latencies are almost always reported as medians. When a distribution is skewed, the median is the more representative center.

The mode is the most frequent value. You count how often each value occurs and keep the value (or values) with the highest count:

const counts = new Map();
for (const x of values) counts.set(x, (counts.get(x) ?? 0) + 1);

const highest = Math.max(...counts.values());
const modes = [...counts].filter(([, n]) => n === highest).map(([x]) => x);

In our set, 15, 18, and 21 each appear twice while everything else appears once, so there are three modes. The opposite case needs care: if every value appears equally often, that snippet would declare every value a mode, which tells you nothing, so a sensible tool reports "no mode" instead. The mode is also the only one of the three that works on categorical data: the most common color, the most common error code. A frequency count does not care about arithmetic, so a mode is defined for any column, numeric or not.

Here is the quick rule of thumb for which center to trust:

SituationBest centerWhy
Roughly symmetric, no outliersMeanUses all data, efficient
Skewed or has outliersMedianResistant to extremes
Categories / non-numericModeOnly one that is defined
You see mean far from medianSuspect skewCompare them on purpose

Take that last row seriously. The gap between mean and median is itself a signal, and Karl Pearson turned it into a number: his second skewness coefficient, 3 * (mean - median) / stdDev. A positive value means the tail points right. For our data it is 3 * (20.1 - 19.5) / 5.666, or about 0.32. Most statistical software, though, means something else by plain "skewness": a moment coefficient built from the average of the cubed standardized deviations. The basic version, the Fisher-Pearson g1, comes out at about 0.35 on the same numbers (some packages apply a small-sample adjustment on top). The two often agree on direction but rarely on size, so check which one a tool reports before comparing figures.

Spread: variance, standard deviation, and the n vs n-1 question

A center tells you nothing about consistency. Test scores of [50, 50, 50] and [0, 50, 100] share a mean of 50 but could not be more different. Variance and standard deviation measure that spread.

Variance is the average of the squared distances from the mean. Squaring does two jobs: it makes every deviation positive (so they do not cancel) and it punishes large deviations more than small ones. Standard deviation is just the square root of variance, which brings the units back to the original scale (dollars instead of dollars-squared).

Here is where the single most common statistics gotcha lives. There are two variance formulas:

Population variance:  sum((x - mean)^2) / n
Sample variance:      sum((x - mean)^2) / (n - 1)

Dividing by n gives the population variance: the true spread when your data is the entire universe you care about. Dividing by n-1 gives the sample variance, used when your data is a sample drawn from a larger population and you want an unbiased estimate of that population's variance. The n-1 (called Bessel's correction) nudges the estimate upward, because a sample tends to cluster a little tighter around its own mean than around the unknown true mean, so dividing by n would underestimate.

In code the two differ by a single term:

const squaredDeviations = values.reduce((acc, x) => acc + (x - mean) ** 2, 0);

const populationVariance = squaredDeviations / values.length;
const sampleVariance = squaredDeviations / (values.length - 1);

const populationSd = Math.sqrt(populationVariance);
const sampleSd = Math.sqrt(sampleVariance);

Which one you get depends entirely on the tool, and a bare label like "Std Dev" rarely tells you. Spreadsheets have both: VAR.P/STDEV.P divide by n (population), while VAR.S/STDEV.S and the older bare VAR and STDEV divide by n-1 (sample). Python's statistics module splits them into pvariance/pstdev and variance/stdev. R's var() and sd() give the sample versions only. If two tools disagree about the standard deviation of the same column, this is almost certainly why.

Here are the numbers for our set, mean 20.1. The squared deviations are:

xx - mean(x - mean)^2
12-8.165.61
15-5.126.01
18-2.14.41
210.90.81
243.915.21
276.947.61
309.998.01
15-5.126.01
18-2.14.41
210.90.81

The squared deviations sum to 288.90. Population variance is 288.90 / 10 = 28.89, and standard deviation is sqrt(28.89) ≈ 5.375. The sample variance divides by 9 instead: 288.90 / 9 = 32.10, giving a standard deviation of about 5.666. Same data, two legitimate answers, and an 11 percent difference in variance (the ratio is always n / (n-1), so 10/9 here). The smaller n is, the bigger the gap, which is exactly when people get burned. At n = 1 the sample variance is not zero but undefined, since n-1 is zero: a single observation cannot tell you anything about spread.

One useful derived measure is the coefficient of variation, the standard deviation divided by the absolute value of the mean, times 100. It expresses spread as a percentage of the mean, so you can compare the consistency of two datasets on different scales (a process measured in millimeters versus one in kilometers). With the sample standard deviation our set comes out at 5.666 / 20.1 * 100 ≈ 28.2%; with the population version it is about 26.7%. It falls apart when the mean is close to zero, and it only makes sense for data where zero means "none", such as weights or durations, not temperatures in Celsius.

Range, quartiles, and IQR

The range is the bluntest spread measure: max - min. For our set, 30 - 12 = 18. It is trivially affected by a single outlier, so it is more a sanity check than an analysis.

Quartiles slice the sorted data into four parts. Q1 (the 25th percentile) is the value a quarter of the way up, Q2 is the median, and Q3 (the 75th percentile) is three quarters of the way up. The interquartile range is Q3 - Q1, the spread of the middle 50 percent of the data. Because IQR throws away the bottom and top quarters entirely, it is far more resistant to outliers than the range or the standard deviation.

The interesting wrinkle is that "the value a quarter of the way up" is not uniquely defined when it falls between two data points. Hyndman and Fan's 1996 paper "Sample Quantiles in Statistical Packages" catalogued nine definitions in common use, and R implements all nine through the type argument of quantile(). They fall into two families: methods that pick an existing data point, and methods that interpolate between two neighbors.

The simplest picking method is nearest rank (Hyndman and Fan's type 1): take the value at rank ceil(n * p), counting from 1.

// Nearest rank: always returns an actual data point
function quantileNearestRank(sorted, p) {
  const rank = Math.max(1, Math.ceil(sorted.length * p));
  return sorted[rank - 1];
}

The most widely used interpolating method (type 7) places the quantile at position (n - 1) * p in a zero-based list and blends the two neighbors linearly:

// Linear interpolation between the two nearest values
function quantileLinear(sorted, p) {
  const pos = (sorted.length - 1) * p;
  const lo = Math.floor(pos);
  const hi = Math.ceil(pos);
  return sorted[lo] + (pos - lo) * (sorted[hi] - sorted[lo]);
}

For our ten sorted values 12, 15, 15, 18, 18, 21, 21, 24, 27, 30:

Nearest rank (type 1)Linear (type 7)
Q1rank ceil(2.5) = 3, so 15position 2.25: 15 + 0.25 * (18 - 15) = 15.75
Q3rank ceil(7.5) = 8, so 24position 6.75: 21 + 0.75 * (24 - 21) = 23.25
IQR24 - 15 = 923.25 - 15.75 = 7.5

Same data, an IQR of 9 or 7.5 depending on the rule. Neither is wrong; they are different conventions for the same question. Type 7 is the default in R, NumPy, and Google Sheets, and it is what Excel's QUARTILE.INC and PERCENTILE.INC compute, which makes it the number a reader is most likely to be able to reproduce. Excel's QUARTILE.EXC uses yet another rule (type 6), which on our data gives Q1 = 15 and Q3 = 24.75. The methods converge as n grows, so the disagreement mostly bites on the small datasets people paste into a calculator.

One shortcut to avoid: sorted[Math.floor(n * p)] looks like nearest rank and happens to agree with it on our ten values, but whenever n * p is a whole number it lands one slot too high. On 1, 2, 3, 4 it reports Q1 = 2, a value that none of the nine published definitions produces.

IQR also powers outlier detection. The classic Tukey rule flags anything below Q1 - 1.5 * IQR or above Q3 + 1.5 * IQR:

const lowerFence = q1 - 1.5 * iqr;
const upperFence = q3 + 1.5 * iqr;
const outliers = sorted.filter(x => x < lowerFence || x > upperFence);

With the type 7 quartiles (Q1 = 15.75, Q3 = 23.25, IQR = 7.5), the fences sit at 15.75 - 11.25 = 4.5 and 23.25 + 11.25 = 34.5. Every value in our set is inside that window, so nothing is flagged. Add a 300 and it sails past the upper fence and gets reported as an outlier, which is the whole point: the fences are derived from the resistant middle of the data, so a single extreme value cannot inflate them and hide itself. Keep in mind that the fences are a convention for drawing box plots, not a statistical test. In a sample of a hundred values from a perfectly normal distribution, expect roughly one to land outside them by chance.

Putting the picture together

No single number describes a distribution, which is why a good summary reports a whole panel at once, ideally next to a histogram. The measures complement each other:

  • Center: mean for symmetric data, median when skewed, mode for categories.
  • Spread: standard deviation for the typical deviation, IQR for the resistant middle, range as a quick bound.
  • Shape: compare mean against median for skew direction; scan for outliers with the IQR fences.

Here is the whole panel for our example:

MeasureValue
Mean20.1
Median19.5
Mode15, 18, 21
Range18
Variance (population / sample)28.89 / 32.10
Std dev (population / sample)~5.375 / ~5.666
Q1 / Q3 (type 7)15.75 / 23.25
IQR (type 7)7.5
Skewness (g1)~0.35

The mean (20.1) sitting just above the median (19.5), together with a small positive skewness, points to a faint right skew. Three tied modes and no values outside the fences describe a fairly flat spread with nothing extreme. That entire read comes from numbers you can compute by hand on ten values, which is why descriptive statistics is the first thing to run and the last thing to skip.

Try it on Loopaloo

If you want to paste numbers and see all of this at once, the Statistics Calculator updates as you type. It shows the mean and median (plus geometric and harmonic means), every tied mode, sample and population variance and standard deviation side by side, quartiles under whichever of the nine definitions you choose (with a table of all nine on request), Tukey's fences, skewness, a histogram with the mean and median marked, and a z-score for any value you enter. Each statistic opens to a short definition and the spreadsheet, Python or R function that reproduces it.

For tabular data, the CSV Statistics Generator profiles every column of a file. Numeric columns get the same measures, text columns get counts, distinct values and a mode, and each column gets a chart of its most frequent values. If you are reconciling against a spreadsheet, compare STDEV.S with the sample figures and STDEV.P with the population ones, and set the quartile definition to type 7 to match QUARTILE.INC.

Related Tools

Related Articles