Descriptive statistics — theory with the campus bus waits, means, quartiles and boxplots (and the bus that never came on a rainy Monday)

My average wait at the campus bus stop came out at 9.3 minutes, but almost every day I waited less than 8: one single bus that never came was enough to inflate it. I found out in the first week of Statistical Methods I (ME1), when I decided to note on my phone how long the bus to Tafira took every time I reached the stop. On Monday it was raining, the 8:10 bus never showed up and I waited thirty-one and a half minutes. On Friday I did the sum, got an average of 9.3 and thought “wow, almost ten minutes every time”. Then I sorted the ten numbers and saw that half of them were below 6.75. That day I understood what this topic is for: a single number does not tell the story of a data set, and you have to know which number to look at.

Today you will learn to describe a data set the way it is done in Statistical Methods I: what population and sample are, how a sample is chosen, how data are organised in tables and charts and which measures summarise their center and their spread. All of it with the 40 waits I noted down that month and with R, which is how it is done in the exam. For every R output I tell you how to read it, number by number, because in the first continuous assessment test (EC1) copying what comes out is not enough: you have to interpret it. If you are not comfortable with R yet, start with R from scratch: vectors and matrices.

Before you start. For this topic all you need is to add up, sort numbers from smallest to largest and know how to create a vector in R with c(). Nothing else. The topic answers four questions, in this order: what data do I have (population, sample and type of variable); how do I organise and draw them (frequency tables, bar charts, stem-and-leaf, histogram); which numbers summarise them (the center, with mean, median and mode; the spread, with variance, standard deviation and interquartile range; and the quartiles, which also give away the odd values); and what do I do if I only have the table and not the data (grouped data). All with the same example: the 40 bus waits.

Population, sample and types of data

Statistics is the science of data: how they are collected, organised, analysed and interpreted, and how models are built to explain their behaviour. This first topic is the descriptive part: summarising what some data you already have are saying.

Two words you will use all year:

  • Population: the complete set of measurements you are interested in. Here, the waits of every bus that will stop at the campus this term. Careful: the population is the measurements (the minutes), not the buses or the students.
  • Sample: a subset of data selected from the population. My 40 waits are a sample. The sample size n n is the number of elements in the sample: n=40 n = 40 .
Population and sampleOn the left, the population: every wait of the term, as a cloud of dots. On the right, the sample of 40 waits. One arrow says the sample is chosen from the population and a dashed one that conclusions about the population are inferred from the sample.Populationevery wait of the termSamplemy 40 waits · n = 40choseninferredTopic 1: describe itTopics 9-11: draw conclusions about it
The population is the measurements you care about; the sample, the ones you have. This topic describes the sample.

Why not study the whole population? Because in the real world you almost never can: I am not going to record the waits of the whole term before knowing how long I wait. The idea of statistics is to draw conclusions about the population from a sample. That is inference (topics 9 to 11); now it is time for the step before: describing the sample well.

Data come in two kinds:

TypeWhat they areAt the bus stopCharts and measures they allow
QuantitativeMeasurements on a numerical scaleMinutes waited: 6.5, 31.5…Histogram, boxplot, mean, variance, quartiles
Categorical (qualitative)Each value falls into a categoryHow the bus arrived: seat free, standing, fullBars, pie, frequencies and mode

Before computing anything, ask yourself what type of variable it is. The mean of “seat free, standing, full” does not exist; the mean of the minutes does.

How a sample is chosen

Whether the sample looks like the population depends on how it is chosen. The lecture notes give three methods:

  • Simple random sampling: you fix the size n n and pick n n elements at random, so that all of them have the same chance of being chosen.
  • Systematic sampling: you number the N N elements of the population from 1 to N N , compute K=N/n K = N/n , pick a random number between 1 and K K and, from it, take one element every K K .
  • Stratified sampling: you split the population into strata according to a criterion (age, sex, income… or the time of day) and, within each stratum, draw a sample with one of the previous methods.

A systematic example with the bus: in a month the bus stops 600 times at the campus and I want a sample of 40 waits. Then K=600/40=15 K = 600/40 = 15 . The random number is 4, so I keep stops 4, 19, 34, 49… and the last one is 4+39⋅15=589 4 + 39 \cdot 15 = 589 . Exactly 40.

Three ways of choosing a sampleThree grids of 30 numbered elements. In simple random sampling, six chosen at random. In systematic sampling with K = 5, starting at 3: elements 3, 8, 13, 18, 23 and 28. In stratified sampling, three strata (morning, midday and evening) with two chosen in each.Simple random4915182629Systematic (K = 5)3813182328Stratified21015222629all equally likelyrandom start (3), every K2 at random per stratum
The coral numbers are the chosen ones. In the systematic one, look at the fixed jump of 5.

Getting the last element of a systematic sample wrong. With 40 elements there are 39 jumps of K K , not 40: the last one is start+(n−1)K \text{start} + (n-1)K . If you get a number bigger than N N , you have made one jump too many.

The three methods, told with the bus. Simple random sampling is putting the 600 stop numbers in a hat and drawing 40. Systematic sampling is drawing only the first one and then following a fixed rule (every 15th): it is handy when the elements come in a row, like the month’s stops one after another. Stratified sampling makes sense when you suspect there are groups that behave differently: waiting at 8:00, in rush hour, is not the same as waiting at 15:00. If you split the stops by time slot (morning, midday, afternoon) and take waits from each one, you make sure no slot is left out by bad luck.

Systematic sampling has a trap: data that repeat with the same rhythm as the jump. If the bus stopped exactly 15 times a day and you took one in every 15, you would always get the same time of day, and your sample would only talk about that hour.

Check you’ve got it: with N = 600, n = 40 and 12 as the random number, which are the first three stops in the sample and which is the last one?

The first three: 12, 27 and 42 (you add K=15 K = 15 each time). The last one is 12+39⋅15=12+585=597 12 + 39 \cdot 15 = 12 + 585 = 597 : 39 jumps, not 40, because the first one already counts. And 597 does not go past 600, so it works. That is why the random number is chosen between 1 and K K : if it were 16, the last one would be 16+585=601 16 + 585 = 601 , a stop that does not exist.

Organising the data: tables and charts

Once you have the data, the first summary is to sort them into a table and draw them. These are my 40 waits, in minutes, in the order I noted them down:

wait <- c(6.5, 4.0, 9.5, 31.5, 7.0, 5.5, 11.0, 8.0, 3.5, 6.5,
          2.5, 4.5, 3.0, 4.5, 1.5, 4.0, 2.0, 5.5, 7.5, 8.5,
          6.0, 9.0, 7.5, 6.5, 8.0, 9.5, 7.0, 8.5, 6.0, 12.0,
          10.5, 13.5, 12.0, 14.5, 12.5, 10.5, 16.5, 18.0, 15.5, 24.0)
length(wait)   # sample size n

Output:

[1] 40

Categorical data: bar and pie charts

Besides the minutes, I noted how each bus arrived. It is a categorical variable, so it is summarised by counting how many times each category appears (its frequency) and drawn with a bar chart (one bar per category, as tall as its frequency) or a pie chart (a circle split into proportional slices).

arrival <- c(rep("Seat free", 17), rep("Standing", 15), rep("Full", 8))
arrival_table <- table(arrival)       # frequency of each category
arrival_table
prop.table(arrival_table)             # relative frequency (f / n)
barplot(arrival_table, ylab = "Number of waits", ylim = c(0, 20))
pie(arrival_table)

Output:

arrival
     Full Seat free  Standing 
        8        17        15 
arrival
     Full Seat free  Standing 
    0.200     0.425     0.375 
Bar and pie charts of how the bus arrivedGraphical output of barplot and pie. Bars: full 8, seat free 17 and standing 15 out of 40 waits. Pie with the same three slices: 20%, 42.5% and 37.5%.05101520Number of waits8Full17Seat free15Standingbarplot(arrival_table)Full20%Seat free42.5%Standing37.5%pie(arrival_table)
What barplot() and pie() draw from the table (redrawn in the site colours): the same information, two ways to read it.

How to read it: out of 40 buses, 17 arrived with free seats, 15 with people standing and 8 so full that they did not let me on. R lists the categories in alphabetical order, so “Full” comes first. prop.table divides each frequency by n=40 n = 40 : 42.5% arrived with free seats and 20% full. In the drawing, the bars show the same as the table and the pie shows it as parts of a whole (the “Full” slice is a fifth of the circle). To compare categories, bars read better: the eye compares heights more precisely than angles.

barplot needs the frequencies, not the data. barplot(arrival) gives an error; barplot(table(arrival)) is right.

The stem-and-leaf plot

For a few quantitative values, the stem-and-leaf plot is a quick summary: each value is split into a stem (the digits on the left) and a leaf (the last digit).

stem(wait)

Output:

  The decimal point is 1 digit(s) to the right of the |

  0 | 2233444
  0 | 556666777778888999
  1 | 001112234
  1 | 5678
  2 | 4
  2 | 
  3 | 2

How to read it, line by line:

  • The decimal point is 1 digit(s) to the right of the |: the stem is the tens. The line 1 | 001112234 reads 10, 10, 11, 11, 11, 12, 12, 13 and 14, already rounded (I explain why in a moment).
  • Each stem appears twice: the first line for 0 holds the leaves 0 to 4 and the second, 5 to 9. R splits it like that when there are many values on few stems.
  • The leaves are rounded to the unit. 1.5 shows as 2, 4.5 as 5, 9.5 as 10 and 31.5 as 32. That is why the first line has 7 leaves even though I have 9 waits below 5: the two 4.5s moved to the next line.
  • What you see at a glance: almost everything is between 2 and 14 minutes, and at the bottom there are two lonely leaves, 24 and 32 (31.5). Those are the odd waits.

The frequency table

With many values, you group them into classes (non-overlapping intervals) and count how many fall into each. If fi f_i is the absolute frequency of class i i and n n the total, the relative frequency is fi/n f_i / n and the cumulative relative frequency of class i i is

Fi=∑k=1ifkn=1n∑k=1ifk F_i = \sum_{k=1}^{i} \frac{f_k}{n} = \frac{1}{n}\sum_{k=1}^{i} f_k

The steps from the notes to build it:

  1. Compute the minimum, the maximum and the range R=max⁡−min⁡ R = \max – \min . Here, R=31.5−1.5=30 R = 31.5 – 1.5 = 30 .
  2. Choose between 5 and 20 classes covering the whole range. The length of each, slightly larger than R/number of classes R / \text{number of classes} .
  3. Start a little below the minimum and end a little above the maximum, so that no value coincides with a class boundary. The midpoint of each class is its class mark.
  4. Count the values in each class.

I used 5-minute classes up to 20 and a wider last one, from 20 to 40, for the two odd waits (many reports build their tables like that, and that is how it comes in the EC1 too). In R, cut assigns each value its class and table counts them:

classes <- cut(wait, breaks = c(0, 5, 10, 15, 20, 40))
f <- table(classes)                      # absolute frequencies
f
round(prop.table(f), 3)                  # relative frequencies
cumsum(prop.table(f))                    # cumulative relative frequencies

Output:

classes
  (0,5]  (5,10] (10,15] (15,20] (20,40] 
      9      18       8       3       2 
classes
  (0,5]  (5,10] (10,15] (15,20] (20,40] 
  0.225   0.450   0.200   0.075   0.050 
  (0,5]  (5,10] (10,15] (15,20] (20,40] 
  0.225   0.675   0.875   0.950   1.000 

How to read it:

  • (0,5] means “greater than 0 and less than or equal to 5″. R opens intervals on the left and closes them on the right: a 5.0 would fall in the first class, not the second. None of my waits lands on a boundary, so there is no doubt.
  • The bottom row holds the fi f_i : 9 waits of up to 5 minutes, 18 between 5 and 10, 8 between 10 and 15, 3 between 15 and 20 and 2 between 20 and 40. They add up to 40.
  • Relative frequencies: 45% of the waits are in the 5-to-10-minute class (18/40=0.45 18/40 = 0.45 ).
  • Cumulative: the 0.675 of the second class says that 67.5% of the time I waited 10 minutes or less; the 0.95 of the fourth, that 95% waited 20 or less. The last one is always 1.

The frequency table, row by row

R gives the three rows separately. Put together in a single table, with the reason for each number, you can see that each column comes from the one before:

ClassMarkfi f_i fi/n f_i / n CumulativeFi F_i Why
(0, 5]2.590.22590.225First class: the cumulative count is its own frequency; 9/40 = 0.225
(5, 10]7.5180.45270.675The 9 from before plus the 18 of this class: 27; and 27/40 = 0.675
(10, 15]12.580.2350.87527 + 8 = 35; 35/40 = 0.875
(15, 20]17.530.075380.9535 + 3 = 38
(20, 40]3020.05401You reach n = 40: the last cumulative value is always 1
Total401The fi f_i add up to n and the relative ones to 1; if not, you have missed a value

The cumulative column can be read in two ways. As it is, Fi F_i answers “what proportion waited at most up to the end of this class?”. And turned around, 1−Fi 1 – F_i answers “what proportion waited longer?”.

Mixing up “the 5-to-10 class” with “up to 10 minutes”. The 45% is only the class (5, 10]; “10 minutes or less” is the cumulative value, 67.5%, because it also includes the 9 waits of the first class.

Check you’ve got it: what percentage of the time did I wait more than 15 minutes?

12.5%. The class (10, 15] ends exactly at 15 and its cumulative value is 0.875: 87.5% of the time I waited 15 minutes or less. What is left, 1−0.875=0.125 1 – 0.875 = 0.125 , is what went past 15. In waits: 0.125⋅40=5 0.125 \cdot 40 = 5 , which are the 3 in the 15-to-20 class plus the 2 in the last one (15.5, 16.5, 18, 24 and 31.5).

The histogram

The histogram draws the table: one bar per class, touching, whose height is the frequency. With classes of different widths there is a detail the exam likes to test:

h <- hist(wait, breaks = c(0, 5, 10, 15, 20, 40),
          main = "Bus waits", xlab = "Minutes")
h$counts     # frequency of each class
h$density    # height of each bar

Output:

[1]  9 18  8  3  2
[1] 0.0450 0.0900 0.0400 0.0150 0.0025
Histogram of the 40 waits with unequal classesHistogram with the classes 0-5, 5-10, 10-15, 15-20 and 20-40 minutes. The heights are densities: 0.045, 0.09, 0.04, 0.015 and 0.0025, with frequencies 9, 18, 8, 3 and 2. The 5 to 10 bar is highlighted: its area, 0.09 times 5, is 0.45.0510152025303540minutes waited00.020.040.060.080.1densityf = 90.045f = 180.09f = 80.04f = 30.015f = 20.0025area0.09 · 5= 0.45wide class: 2 valuesover 20 minutes
With unequal classes, the height is the density and the area of each bar is its relative frequency.

How to read it: since the classes do not have the same width, R does not draw the frequency but the density: fi/(n⋅width) f_i / (n \cdot \text{width}) . The 5-to-10 class is 18/(40⋅5)=0.09 18 / (40 \cdot 5) = 0.09 tall and the 20-to-40 class, 2/(40⋅20)=0.0025 2 / (40 \cdot 20) = 0.0025 . That way the area of each bar is its relative frequency (0.09⋅5=0.45 0.09 \cdot 5 = 0.45 ) and a wide class does not look more important than it is. If you drew the frequencies, the 20-to-40 bar (2 values) would cover a 20-minute gap and fool the eye. The shape you see: a peak between 5 and 10 minutes and a long tail to the right. The data are skewed: many short waits and a few very long ones.

The density, class by class. The height is the relative frequency spread over the width, and the area (width times height) gives the relative frequency back:

ClassWidthfi/n f_i / n Height (density)AreaWhy
(0, 5]50.2250.0450.2250.225 / 5 = 0.045
(5, 10]50.450.090.45The tallest bar: it is the peak of the histogram
(10, 15]50.20.040.20.2 / 5 = 0.04
(15, 20]50.0750.0150.0750.075 / 5 = 0.015
(20, 40]200.050.00250.05Wide and very low: two values spread over 20 minutes

The areas add up to 1, just like the relative frequencies. One way to picture it: each bar is a pile of sand with as many grains as values in its class. If you spread the same pile over a base four times wider, it ends up four times lower. That is what R does with the 20-to-40 class.

If the exam gives you a density histogram and asks how many values there are in a class, the calculation is height times width times n. For the last one: 0.0025⋅20⋅40=2 0.0025 \cdot 20 \cdot 40 = 2 .

With equal classes, hist draws frequencies on the vertical axis (Frequency). If you want densities with equal classes, add freq = FALSE. In the exam, always look at the axis label before reading the heights.

Measures of center: mean, median and mode

Before the formulas: three questions for the week

Before the definitions, go back to the week of the rainy Monday: 6.5 · 4 · 9.5 · 31.5 · 7 · 5.5 · 11 · 8 · 3.5 · 6.5. How long do I “normally” wait? There are three reasonable ways to answer, and each one is a measure:

  • If I shared the total out equally. That week I waited 93 minutes in total. Shared among the 10 buses, that is 9.3 each. That is the mean: the total, shared out.
  • If I keep the wait in the middle. I sort the 10 and look at which one is in the center. With 10 values there is no single center: there are two, the 5th and the 6th (6.5 and 7), and the median is their midpoint, 6.75. With 9 values there would be just one, the 5th.
  • If I keep the one that repeats most. 6.5 appears twice and the rest once. The mode is 6.5.

Three answers and three different numbers (9.3, 6.75 and 6.5), and none of them is wrong: they answer different questions. The mean is the only one that notices how big the 31.5 is; for the median it is just “the largest” and for the mode, “one that does not repeat”.

To find the center with many values, the position: with n n odd it is value number (n+1)/2 (n+1)/2 of the sorted sample; with n n even, the mean of values n/2 n/2 and n/2+1 n/2 + 1 . With the 40 waits those are values 20 and 21, which are 7.5 and 8: M=(7.5+8)/2=7.75 M = (7.5 + 8)/2 = 7.75 . It is the same 7.75 that R gives a little further down.

Giving the position instead of the value, or looking for it without sorting. “The median is 20.5” makes no sense: 20.5 says where it is (between values 20 and 21), not how much it is. And value 20 of the unsorted list is an 8.5 that means nothing.

For a data set x1,…,xn x_1, \dots, x_n :

  • The sample mean is the sum of the data divided by n n :
xˉ=1n∑i=1nxi \bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i
  • The median (M M , Q2 Q_2 or 50th quantile) is the value in the central position of the sorted sample. If n n is even, the mean of the two central ones.
  • The mode is the most frequent value. If all values are different, there is no mode.

By hand, with the first week (the first 10 values): they add up to 93, so xˉ=93/10=9.3 \bar{x} = 93/10 = 9.3 . Sorted they are 3.5 · 4 · 5.5 · 6.5 · 6.5 · 7 · 8 · 9.5 · 11 · 31.5; the central ones are the 5th and the 6th, so M=(6.5+7)/2=6.75 M = (6.5 + 7)/2 = 6.75 . And with R, all 40:

mean(wait)                       # mean
median(wait)                     # median
sort(table(wait), decreasing = TRUE)[1:3]   # the 3 most repeated values

Output:

[1] 9.1
[1] 7.75
wait
6.5   4 4.5 
  3   2   2 

How to read it: on average I wait 9.1 minutes, but half of the time I wait 7.75 or less. The sorted table says that 6.5 appears 3 times and nothing appears more often: the mode is 6.5 minutes (with continuous data the mode says little: with more decimals, every wait would be different).

Why is the mean larger than the median? Because the mean uses the value of each observation and the median only its position. The two odd waits (24 and 31.5) pull the mean up, but the median does not care how big they are: they are still “the two largest”. If Monday’s bus had taken 60 minutes, the mean would rise to 9.81 and the median would stay at 7.75.

Mean and median of the 40 waitsDot plot of the 40 waits on an axis from 0 to 35 minutes, with repeated values stacked. A green line marks the median, 7.75, and a coral triangle under the axis marks the mean, 9.1, as the balance point. The waits of 24 and 31.5 minutes are in coral.05101520253035minutesmedian 7.75mean 9.1the two odd waitspull the mean up
The mean is the balance point: the two far values shift it to the right; the median only looks at positions.

Giving the mean as “the usual value” with skewed data or with outliers. The notes say it clearly: if there are extreme values, the mean may not be a good measure of center. With a tail to the right, mean > median; with a tail to the left, the other way round. Comparing them is the quickest way to spot skewness.

Measures of spread: variance and standard deviation

Two data sets can have the same mean and look nothing alike: always waiting 9 minutes is not the same as sometimes waiting 2 and sometimes 30. Spread measures how far the data are from their mean.

The idea in words: how far each wait strays

Before the formula, the recipe. Measuring spread is answering “how far do my waits stray from the mean?”, and it takes five steps:

  1. Measure the distance from each value to the mean. That is the deviation xi−xˉ x_i – \bar{x} . In the week, the 6.5 is 2.8 below 9.3 and the 31.5 is 22.2 above it.
  2. Do not add them as they are. The ones below are negative, the ones above positive, and they cancel out: they always add up to 0. An average of deviations would always be 0, whether there was little or a lot of spread.
  3. Get rid of the sign. There are two ways. With the absolute value you get the mean deviation. Squaring gives the variance, which is the one used because the square is much easier to handle in calculations and in proofs.
  4. Average, but divide by n−1 n-1 . That is the sample variance s2 s^2 . Why n−1 n-1 and not n n becomes clear in topic 10; for now, just keep in mind that the notes and R do it that way.
  5. Undo the square. The variance is in minutes squared. Its square root, the standard deviation s s , goes back to minutes, and it is the one you interpret.
  • Sample variance:
s2=1n−1∑i=1n(xi−xˉ)2 s^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i – \bar{x})^2
  • Sample standard deviation: s=s2 s = \sqrt{s^2} . It is in the same units as the data (minutes), which is why it is the one you interpret.
  • Mean deviation: MD=1n∑i=1n∣xi−xˉ∣ MD = \frac{1}{n}\sum_{i=1}^{n}|x_i – \bar{x}| , the average distance to the mean.

By hand, with the first week (xˉ=9.3 \bar{x} = 9.3 ):

xi x_i 6.549.531.575.51183.56.5
xi−xˉ x_i – \bar{x} −2.8−5.30.222.2−2.3−3.81.7−1.3−5.8−2.8
(xi−xˉ)2 (x_i – \bar{x})^2 7.8428.090.04492.845.2914.442.891.6933.647.84

Look at the second row: the deviations add up to exactly 0 (24.1−24.1 24.1 – 24.1 ). It always happens, and that is why they are useless as a plain sum: you square them. The third row adds up to 594.6, so s2=594.6/9=66.07 s^2 = 594.6/9 = 66.07 and s=66.07=8.13 s = \sqrt{66.07} = 8.13 minutes. Of that 594.6, the 31.5 contributes 492.84: 83% of the week’s variance is the fault of a single bus.

Check you’ve got it: what would the mean and the standard deviation of the week be without Monday’s bus?

There are 9 values left that add up to 93−31.5=61.5 93 – 31.5 = 61.5 , so xˉ=61.5/9=6.83 \bar{x} = 61.5/9 = 6.83 . For the variance the shortcut formula a little further down is the handy one: from the week’s sum of squares you take away the square of 31.5, 1459.5−31.52=1459.5−992.25=467.25 1459.5 – 31.5^2 = 1459.5 – 992.25 = 467.25 . Then s2=(467.25−61.52/9)/8=(467.25−420.25)/8=47/8=5.88 s^2 = (467.25 – 61.5^2/9)/8 = (467.25 – 420.25)/8 = 47/8 = 5.88 (you divide by 8 because now n−1=8 n – 1 = 8 ) and s=2.42 s = 2.42 minutes.

The mean drops from 9.3 to 6.83, but the standard deviation plunges from 8.13 to 2.42: a single bus was multiplying s s by more than 3. Spread is even more sensitive to an odd value than the mean, because it squares it.

There is a shortcut formula that avoids subtracting the mean from each value and is the one to use by hand:

s2=1n−1[∑i=1nxi2−1n(∑i=1nxi)2] s^2 = \frac{1}{n-1}\left[\sum_{i=1}^{n} x_i^2 – \frac{1}{n}\left(\sum_{i=1}^{n} x_i\right)^2\right]

With the week: ∑xi2=1459.5 \sum x_i^2 = 1459.5 and ∑xi=93 \sum x_i = 93 , so s2=(1459.5−932/10)/9=(1459.5−864.9)/9=66.07 s^2 = (1459.5 – 93^2/10)/9 = (1459.5 – 864.9)/9 = 66.07 . The same. In R, var and sd use n−1 n-1 :

var(wait)                           # sample variance (divides by n - 1)
sd(wait)                            # standard deviation
mean(abs(wait - mean(wait)))        # mean deviation
week <- wait[1:10]
sum(week - mean(week))              # the deviations add up to 0

Output:

[1] 35.4
[1] 5.94979
[1] 4.225
[1] -7.105427e-15

How to read it:

  • 35.4: the variance is in squared minutes, a unit that means nothing at the bus stop. It is for calculations, not for interpreting.
  • 5.94979: the standard deviation. My waits are, broadly speaking, about 5.95 minutes away from the mean. With 2 decimals, as in the exam: s=5.95 s = 5.95 .
  • 4.225: the mean deviation. On average, each wait is 4.225 minutes from the mean. It is smaller than s s because s s squares and gives more weight to large deviations (the 31.5 again).
  • -7.105427e-15: that is −7.1⋅10−15 -7.1 \cdot 10^{-15} , that is, zero. The computer stores decimals with a tiny error; whenever you see e-15 or e-16 in a calculation that should give 0, it does give 0.

Dividing by n n instead of n−1 n-1 . The sample variance in the notes, and in var(), divides by n−1 n-1 . If you compute it by hand with mean((x - mean(x))^2) you get 34.515 instead of 35.4 and it does not match R. Why n−1 n – 1 is better will come in topic 10 (unbiased estimators).

The properties of the variance given in the notes (s2≥0 s^2 \ge 0 , the deviations add up to 0 and the shortcut formula) are proved in the exam. You have them step by step in the proofs for this topic.

Quartiles, interquartile range and outliers

The median splits the sorted data into two halves. The quartiles split them into four:

  • First quartile Q1 Q_1 : leaves 25% of the sorted data to its left.
  • Q2 Q_2 is the median.
  • Third quartile Q3 Q_3 : leaves 25% to its right (75% to its left).
  • Interquartile range: IQR=Q3−Q1 IQR = Q_3 – Q_1 . It measures the width of the central 50% and, unlike the variance, extremes do not affect it.

Quartiles are used to look for possible outliers: any value satisfying

x≤Q1−1.5 IQRorx≥Q3+1.5 IQR x \le Q_1 – 1.5\,IQR \quad \text{or} \quad x \ge Q_3 + 1.5\,IQR

The two limits are called fences: anything outside them is suspected of not following the pattern of the rest.

q <- quantile(wait)            # minimum, Q1, median, Q3 and maximum
q
IQR_w <- IQR(wait)             # Q3 - Q1
IQR_w
LB <- q[2] - 1.5 * IQR_w       # lower fence
UB <- q[4] + 1.5 * IQR_w       # upper fence
c(LB, UB)
wait[wait < LB | wait > UB]    # possible outliers

Output:

   0%   25%   50%   75%  100% 
 1.50  5.50  7.75 11.25 31.50 
[1] 5.75
   25%    75% 
-3.125 19.875 
[1] 31.5 24.0

How to read it:

  • quantile on its own gives five numbers: the minimum (0%), Q1 Q_1 (25%), the median (50%), Q3 Q_3 (75%) and the maximum (100%). 25% of the time I waited 5.5 minutes or less and 75% of the time, 11.25 or less.
  • IQR=11.25−5.5=5.75 IQR = 11.25 – 5.5 = 5.75 : the central 50% of my waits fits in a window of less than 6 minutes.
  • The fences: 5.5−1.5⋅5.75=−3.125 5.5 – 1.5 \cdot 5.75 = -3.125 and 11.25+1.5⋅5.75=19.875 11.25 + 1.5 \cdot 5.75 = 19.875 . Below there is nothing to look for (there are no negative waits); above, 31.5 and 24 go past 19.875: they are the possible outliers. 18, the next largest, stays inside.
  • The 25% printed above -3.125 is only the name dragged along by q[2]; it is not data. To remove it, unname(q[2]).

For the curious. With 40 values, 25% does not fall exactly on a data point. R (by default, “type 7”) puts the quantile p p at position h=(n−1)p+1 h = (n-1)p + 1 of the sorted sample and interpolates between the two neighbours. For Q3 Q_3 : h=39⋅0.75+1=30.25 h = 39 \cdot 0.75 + 1 = 30.25 , that is, value 30 (11) plus a quarter of the jump to value 31 (12): 11+0.25⋅1=11.25 11 + 0.25 \cdot 1 = 11.25 . By hand there are other rules that give slightly different values; in the exam, R’s rule is used.

The three quartiles, step by step

R’s rule, applied to the three quartiles. You need the sorted sample, and only six of its values: the 10th and 11th (5.5 and 5.5), the 20th and 21st (7.5 and 8) and the 30th and 31st (11 and 12).

Quartileh=39p+1 h = 39p + 1 NeighboursCalculationWhy
Q1 Q_1 , with p=0.25 p = 0.25 10.75value 10 = 5.5; value 11 = 5.55.5 + 0.75 · 0 = 5.5Both neighbours are equal: it does not matter how far you move between them
Q2 Q_2 , with p=0.5 p = 0.5 20.5value 20 = 7.5; value 21 = 87.5 + 0.5 · 0.5 = 7.75Halfway: it is the mean of the two central values, the usual median
Q3 Q_3 , with p=0.75 p = 0.75 30.25value 30 = 11; value 31 = 1211 + 0.25 · 1 = 11.25A quarter of the jump from 11 to 12

The whole part of h h tells you which value you start from, and the decimals, what fraction of the jump to the next one you move.

And the fences, in words: “1.5 IQR” is one and a half times the width of the box, measured from the edges of the box outwards (not from the median). Above, 11.25+1.5⋅5.75=11.25+8.625=19.875 11.25 + 1.5 \cdot 5.75 = 11.25 + 8.625 = 19.875 . Anything past that is too far from the bulk of the data not to be suspicious.

Check you’ve got it: with the fences of these 40 values, would a 20-minute wait be a possible outlier? And a 19-minute one?

The 20, yes, only just: 20≥19.875 20 \ge 19.875 . The 19, no: it stays inside the fence, and if it were in the data the right whisker would reach it instead of stopping at 18.

One detail: the question uses the current fences. If you actually added the 20 to the sample, n would become 41 and the quartiles would be recalculated. R gives Q3=12 Q_3 = 12 , IQR=6.5 IQR = 6.5 and the upper fence goes up to 21.75, so the 20 would no longer be an outlier. The fences depend on the data: they are not a fixed number.

The boxplot

The boxplot, or box-and-whisker plot, draws all of the above at once:

b <- boxplot(wait, horizontal = TRUE, xlab = "Minutes waited")
b$stats      # lower whisker, box (3 lines) and upper whisker
b$out        # the loose points: possible outliers

Output:

      [,1]
[1,]  1.50
[2,]  5.50
[3,]  7.75
[4,] 11.50
[5,] 18.00
[1] 31.5 24.0
Annotated boxplot of the 40 waitsHorizontal boxplot: left whisker at 1.5; box from 5.5 to 11.5 with the median at 7.75; right whisker up to 18, the last value inside the fence at 19.875, drawn as a dashed line; and two red circles at 24 and 31.5, the possible outliers.05101520253035minutesfence 19.8751.5Q1 = 5.5median 7.7511.518whisker: last valueinside the fencepossible outliers2431.5
The right whisker stops at 18, not at the maximum: anything beyond the fence is drawn on its own.

How to read it, from left to right:

  • Left whisker (1.5): it reaches the smallest value inside the fence. Here it is the minimum.
  • Box: from 5.5 to 11.5, with the median (7.75) inside. The box holds the central 50% of the data.
  • Right whisker (18): it reaches the largest value inside the fence, not the maximum. That is the most common mistake when reading a boxplot.
  • Loose points (24 and 31.5): the possible outliers, drawn one by one.
  • The median is closer to the left edge of the box and the right whisker is longer: right skewness again.

For the curious. Why does the box end at 11.5 if Q3=11.25 Q_3 = 11.25 ? boxplot does not use quantile but Tukey’s “hinges” (fivenum): the median of each half of the data. With n=40 n = 40 , the upper half is values 21 to 40 and its median is (11+12)/2=11.5 (11 + 12)/2 = 11.5 . They are almost always very close; if the exam asks for Q3 Q_3 , give it with quantile and do not read it off the plot.

summary puts almost everything in this topic on one line:

summary(wait)

Output:

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.50    5.50    7.75    9.10   11.25   31.50 

How to read it: Min. and Max. are 1.5 and 31.5; 1st Qu. and 3rd Qu. are Q1 Q_1 and Q3 Q_3 (the same as quantile, not the boxplot ones); Median 7.75 and Mean 9.1. Mean above the median and a maximum very far from Q3 Q_3 : just by looking at this line you know there is a right tail and some odd value.

The empirical rule

The mean and the standard deviation are used so much because, when the histogram has a roughly symmetric bell shape, they satisfy a practical rule:

  • About 68% of the data lie in (xˉ−s, xˉ+s) (\bar{x} – s,\ \bar{x} + s) .
  • About 95%, in (xˉ−2s, xˉ+2s) (\bar{x} – 2s,\ \bar{x} + 2s) .
  • About 99.7%, in (xˉ−3s, xˉ+3s) (\bar{x} – 3s,\ \bar{x} + 3s) .

Does it hold for my waits? I count with R:

m <- mean(wait); s <- sd(wait)
c(mean(abs(wait - m) < s),          # proportion within 1 s
  mean(abs(wait - m) < 2 * s),      # within 2 s
  mean(abs(wait - m) < 3 * s))      # within 3 s

Output:

[1] 0.775 0.950 0.975
The empirical rule with the 40 waitsThree bands centred on the mean 9.1: at one, two and three standard deviations (5.95). To the left of each band, what percentage of the waits it contains and what the empirical rule would say: 77.5% against 68%, 95% against 95% and 97.5% against 99.7%. Below, the 40 waits as dots.-100102030minutesx̄ ± 1s: 77.5% of the waitsthe rule would say 68%x̄ ± 2s: 95% of the waitsthe rule would say 95%x̄ ± 3s: 97.5% of the waitsthe rule would say 99.7%mean 9.1
With skewed data the rule does not fit: too many waits near the mean and one beyond 3s.

How to read it: abs(wait - m) < s gives a TRUE for each value less than one deviation from the mean, and the mean of a logical vector is the proportion of TRUE. I get 77.5% instead of 68%, exactly 95% in the second and 97.5% instead of 99.7%: the rule does not fit because my data are not bell-shaped (right tail). Not fitting is a conclusion, not a mistake: the rule only holds for symmetric, bell-shaped data, and checking it like this is a good exam question. The real bell, the normal distribution, arrives in topic 5.

Grouped data

Sometimes all you have is the frequency table: a bus company report, a published study, an exam question. Then you use the class marks mi m_i (the midpoint of each class) as if every value in the class were worth that. With K K classes of frequencies fi f_i and n=∑fi n = \sum f_i :

xˉ=1n∑i=1Kfi mi \bar{x} = \frac{1}{n}\sum_{i=1}^{K} f_i\, m_i
s2=1n−1∑i=1Kfi (mi−xˉ)2=1n−1[∑i=1Kfi mi2−1n(∑i=1Kfi mi)2] s^2 = \frac{1}{n-1}\sum_{i=1}^{K} f_i\,(m_i – \bar{x})^2 = \frac{1}{n-1}\left[\sum_{i=1}^{K} f_i\, m_i^2 – \frac{1}{n}\left(\sum_{i=1}^{K} f_i\, m_i\right)^2\right]

And the median is approximated by interpolating inside the class that contains it:

M=L+wfm(n2−Fb) M = L + \frac{w}{f_m}\left(\frac{n}{2} – F_b\right)

where L L is the lower limit of the median class, w w its width, fm f_m its frequency and Fb F_b the (absolute) cumulative frequency of all the classes before it.

With my table (classes 0-5, 5-10, 10-15, 15-20 and 20-40): the marks are 2.5, 7.5, 12.5, 17.5 and 30 (careful, the last is (20+40)/2=30 (20 + 40)/2 = 30 , not 22.5). The median is the value that leaves 20 on each side (n/2=20 n/2 = 20 ); the first class accumulates 9 and the second reaches 9+18=27≥20 9 + 18 = 27 \ge 20 , so it is in the second: L=5 L = 5 , w=5 w = 5 , fm=18 f_m = 18 , Fb=9 F_b = 9 .

M=5+518 (20−9)=5+3.06=8.06 M = 5 + \frac{5}{18}\,(20 – 9) = 5 + 3.06 = 8.06
f <- c(9, 18, 8, 3, 2)                   # frequencies from the table
m <- c(2.5, 7.5, 12.5, 17.5, 30)          # class marks
n <- sum(f)
mean_gr <- sum(f * m) / n
mean_gr
var_gr <- sum(f * (m - mean_gr)^2) / (n - 1)
round(c(var_gr, sqrt(var_gr)), 2)
cumsum(f)                                 # cumulative: the median is where n/2 = 20 is passed
M <- 5 + 5 / 18 * (n / 2 - 9)
round(M, 2)

Output:

[1] 9.25
[1] 41.41  6.44
[1]  9 27 35 38 40
[1] 8.06
The median of grouped data, by interpolationCumulative frequency polygon of the waiting-time table: 0 at 0, 9 at 5, 27 at 10, 35 at 15, 38 at 20 and 40 at 40 minutes. A horizontal line at 20 (half of the data) crosses the segment between 5 and 10 at 8.06, the median.0510152025303540minutes010203040cumulative927353840n/2 = 20M = 8.06L = 5, w = 5F_b = 9, f_m = 18
The median is where the cumulative count reaches n/2: inside the 5 to 10 segment, 11/18 of the way along.

How to read it: with the table, the mean is 9.25, the variance 41.41, the standard deviation 6.44 and the median 8.06. With the 40 values they were 9.1, 35.4, 5.95 and 7.75. They are close, but not equal, and that is what you would expect: grouping loses information, because each value becomes its class mark. Here the biggest difference is in the wide class: its two values (24 and 31.5) both become 30, which raises the mean and, above all, the variance. That is exactly what the exam asks: compute with the table and compare with the original data, explaining why they do not match.

In the grouped median, including the frequency of the median class itself in Fb F_b (Fb=27 F_b = 27 ) or using the upper limit as L L . Fb F_b is what has been accumulated before entering the class; if your median falls outside its class, you have used L L or Fb F_b wrongly.

The grouped mean and variance, by hand

In the exam this part usually comes on paper. The working table has one column for each sum the formulas ask for:

Classmi m_i fi f_i fi mi f_i\, m_i fi mi2 f_i\, m_i^2 Why
(0, 5]2.5922.556.25The 9 waits all become 2.5
(5, 10]7.5181351012.518 · 7.5 = 135, and 135 · 7.5 = 1012.5: the previous column times the mark again
(10, 15]12.5810012508 · 12.5 = 100; 100 · 12.5 = 1250
(15, 20]17.5352.5918.753 · 17.5 = 52.5; 52.5 · 17.5 = 918.75
(20, 40]302601800The two odd waits, as if both were 30 minutes
Sum403705037.5The three sums you need

The mean: xˉ=370/40=9.25 \bar{x} = 370/40 = 9.25 . The variance, with the shortcut formula:

s2=139[5037.5−370240]=5037.5−3422.539=161539=41.41 s^2 = \frac{1}{39}\left[5037.5 – \frac{370^2}{40}\right] = \frac{5037.5 – 3422.5}{39} = \frac{1615}{39} = 41.41

and s=41.41=6.44 s = \sqrt{41.41} = 6.44 . The same 9.25, 41.41 and 6.44 that R gave.

Use the shortcut formula here too. With the other one you would have to subtract 9.25 from each mark and square five numbers with decimals. And do not forget the weights: adding up the mi2 m_i^2 without multiplying by fi f_i treats each class as if it had a single value.

What is proved in this topic

The proposed exercises and the ME1 exams ask for short proofs of these results. Here you have the statement and the idea; the full step-by-step development is in Descriptive statistics: proofs.

ResultIdea of the proof
∑(xi−xˉ)=0 \sum (x_i – \bar{x}) = 0 Split the sum and use ∑xi=nxˉ \sum x_i = n\bar{x}
Shortcut formula for s2 s^2 Expand the square (xi−xˉ)2 (x_i – \bar{x})^2 and use ∑xi=nxˉ \sum x_i = n\bar{x} again
Change of origin and scale: if y=a+bx y = a + bx , yˉ=a+bxˉ \bar{y} = a + b\bar{x} and sy=∣b∣ sx s_y = |b|\,s_x Substitute into the definitions; the constant a a cancels out in the deviations
Grouped data: ∑fi(mi−xˉ)=0 \sum f_i (m_i – \bar{x}) = 0 Same as the first one, with weights fi f_i
The mean minimises ∑(xi−a)2 \sum (x_i – a)^2 Add and subtract xˉ \bar{x} inside the bracket
Mean and variance of several groups togetherSplit the sum by groups and use the previous result in each one

Common mistakes

Computing the mean of a categorical variable. If the data are “seat free”, “standing” and “full”, you count them (frequencies, mode), you do not average them.

Reading the boxplot whisker as the maximum. The whisker ends at the last value inside the fence; outliers are drawn separately.

Comparing the heights of a histogram with unequal classes as if they were frequencies. With classes of different width, R draws densities and what counts is the area.

Giving the variance as a measure of spread “in minutes”. It is in squared minutes: to interpret, use the standard deviation.

summary(x) before anything else. In one line you see whether the mean moves away from the median (skewness) and whether the maximum or the minimum are very far from the quartiles (possible outliers).

Try it in the R playground

This topic is easier to understand by playing with the data. Open the site’s R playground (it runs in the browser, nothing to install) and paste this script:

wait <- c(6.5, 4.0, 9.5, 31.5, 7.0, 5.5, 11.0, 8.0, 3.5, 6.5,
          2.5, 4.5, 3.0, 4.5, 1.5, 4.0, 2.0, 5.5, 7.5, 8.5,
          6.0, 9.0, 7.5, 6.5, 8.0, 9.5, 7.0, 8.5, 6.0, 12.0,
          10.5, 13.5, 12.0, 14.5, 12.5, 10.5, 16.5, 18.0, 15.5, 24.0)
summary(wait)
round(c(mean = mean(wait), sd = sd(wait)), 2)
wait[4] <- 60          # what if Monday's bus had taken an hour?
summary(wait)
boxplot(wait, horizontal = TRUE)
hist(wait, breaks = c(0, 5, 10, 15, 20, 60))

What to look at:

  1. In the Environment tab, wait appears with its 40 values. Click on it to see it as a table.
  2. Compare the two summary outputs: when 31.5 becomes 60, the mean rises from 9.1 to 9.81 and the median does not move from 7.75.
  3. In Plots, the loose point of the boxplot moves to 60, but the box and the whiskers are the same.
  4. In the histogram, the last class now goes from 20 to 60: see how its height (density) drops as it gets wider.
  5. Type ?quantile in the console and look for the Types section: there are the nine ways R has of computing quartiles.

Summary

ConceptWhat it isIn R
Mean xˉ \bar{x} Sum divided by n n ; affected by extremesmean(x)
Median M M The central value of the sorted datamedian(x)
ModeThe most frequent valuetable(x)
Variance s2 s^2 Squared deviations divided by n−1 n-1 ; in units²var(x)
Standard deviation s s s2 \sqrt{s^2} , in the units of the datasd(x)
Quartiles and IQR IQR 25%, 50%, 75%; IQR=Q3−Q1 IQR = Q_3 – Q_1 quantile(x), IQR(x)
OutliersOutside [Q1−1.5 IQR, Q3+1.5 IQR] [Q_1 – 1.5\,IQR,\ Q_3 + 1.5\,IQR] boxplot(x)$out
Frequency tableClasses, fi f_i , fi/n f_i/n , cumulativetable(cut(x, breaks))
Grouped dataClass marks with weights fi f_i ; interpolated mediansum(f * m) / n

Three ideas to take away:

  1. A single number does not describe a data set: compare mean and median, and look at the spread.
  2. In R almost everything comes out in one line (summary, quantile, table(cut(...))); what earns marks is reading it in the context of the problem.
  3. With grouped data the measures are approximate: compute, compare with the original data and explain the difference.

Next, it is time to prove the properties in this topic: in Descriptive statistics: proofs you have them step by step. After that, in the R practice you will analyse a whole month of waits by time slot. And to check you have got it, the descriptive statistics exercises are EC1-style questions with their marks and commented solutions.

Next step: proofsDescriptive statistics — step-by-step proofs with the bus waits: deviations that add up to zero, the short variance formula and the mean of several groups (and the variance I divided by n)

Did this article help you? Here is how you can support SergioLearns →