Descriptive statistics — R practice with the bus waits by time slot: summary, tables with cut and boxplots by group (and the cut() that swallowed the shortest wait)
My first frequency table in R added up to 59 and I had 60 waits: cut had swallowed the shortest one without a warning. It was in the second ME1 lab session. I had recorded the bus waits of a whole month, by time slot, and I did what the notes say: range, five classes, length rounded up. I started the breaks at the minimum, 2.5, which seemed the most natural thing to do. The table looked nice, so did the histogram, and the grouped mean did not match anything. When I added up the frequencies I saw the 59. The 2.5 was the left end of the first class, and in R classes are (a, b]: open on the left. The smallest value did not fit in any class and R had quietly left it out.
In the descriptive statistics theory you saw each measure with my 40 waits, and in the proofs, where their formulas come from. Here you will do what is done in the ME1 lab sessions: three R scripts, intermediate level, with 60 waits from one month split into three time slots (morning, midday and evening). They are data like real ones: with a full bus that went straight past, one that never came and waits that land right on a class boundary. For every output I explain how to read it, number by number.
Table of Contents
Before you start
You should be clear about:
- Creating vectors with
c()and data frames withdata.frame()(R from scratch). - What the mean, the median, the variance, the quartiles and the interquartile range are, and the rule for possible outliers.
- How a frequency table is built and how to compute the mean, the variance and the median with grouped data.
- The formula for the mean and variance of several groups (proof 6).
If any of them sounds shaky, review the theory before carrying on.
Write each program in a script (.R) and run it line by line with Ctrl+Enter, as you will in the exam. You can use RStudio or the site’s R playground. Results, with 2 decimals: round(x, 2).
Program 1: the morning summary
The first script summarises the 20 waits of the morning slot (from 7:30 to 9:00, the campus rush hour): the measures of center and spread, the quartiles, the possible outliers and how everything changes if the odd value is removed.
The idea
The order matters: first look (how many values and a quick summary), then measure (center and spread in a named vector, so the output reads by itself), then look for anything odd (fences and outliers) and, finally, decide how much the odd value weighs by repeating the summary without it. That last step is the one that answers the exam question “comment” or “interpret”.
Before programming, think about what you expect to find: at rush hour, somewhat longer waits than at midday and the odd full bus that does not stop.
The code
morning <- c(8.5, 12.0, 6.5, 14.5, 9.0, 21.5, 7.5, 11.0, 10.5, 13.0,
5.5, 9.5, 16.0, 8.0, 12.5, 6.5, 10.0, 15.5, 9.0, 11.5)
n <- length(morning)
# Center and spread in a named vector: the output says what each number is
overview <- c(n = n, mean = mean(morning), median = median(morning),
s2 = var(morning), s = sd(morning), IQR = IQR(morning))
round(overview, 2)
quantile(morning) # the quartiles with R's rule (type 7)
fivenum(morning) # the "hinges" that boxplot() uses
# 1.5 IQR fences; unname() drops the "25%" name that quantile drags along
q1 <- quantile(morning, 0.25); q3 <- quantile(morning, 0.75)
fences <- unname(c(q1 - 1.5 * IQR(morning), q3 + 1.5 * IQR(morning)))
fences
morning[morning < fences[1] | morning > fences[2]] # possible outliers
which(morning > fences[2]) # at which position
# How much does the outlier weigh? The same summary without value 6
round(c(mean_without = mean(morning[-6]), median_without = median(morning[-6]),
s_without = sd(morning[-6])), 2)
stem(morning)
boxplot(morning, horizontal = TRUE, xlab = "Minutes waited (morning)")
Output
n mean median s2 s IQR
20.00 10.90 10.25 14.99 3.87 4.25
0% 25% 50% 75% 100%
5.500 8.375 10.250 12.625 21.500
[1] 5.50 8.25 10.25 12.75 21.50
[1] 2 19
[1] 21.5
[1] 6
mean_without median_without s_without
10.34 10.00 3.04
The decimal point is 1 digit(s) to the right of the |
0 | 67788999
1 | 00112233
1 | 566
2 | 2
How to read it
Line by line:
n 20, mean 10.90, median 10.25: in the morning I wait 10.9 minutes on average, and half the days 10.25 or less. The mean is somewhat above the median: something is pulling it up.s2 14.99, s 3.87: the variance in squared minutes (not to be interpreted) and the standard deviation, 3.87 minutes.IQR 4.25: the central 50% of the morning waits fits in 4.25 minutes (from 8.375 to 12.625).quantilegives and ;fivenum, the hinges 8.25 and 12.75. Close but not equal (with 20 values, falls at position and R interpolates between the 5th and the 6th).- Fences: and . Only 21.5 falls outside, and
whichsays it is the 6th value: the Thursday when two full buses went past in a row without stopping. - Without value 6, the mean drops from 10.9 to 10.34 (more than half a minute), the median barely moves (from 10.25 to 10) and the standard deviation falls from 3.87 to 3.04. A single value moves the standard deviation by 21%: that is why you look for it before interpreting.
- In the stem-and-leaf plot, everything is between 6 and 16 except one lonely leaf on the line of 2: 22 (21.5 rounded).
And the boxplot (look at the drawing): box from 8.25 to 12.75 with the median at 10.25, almost in the middle; right whisker up to 16, the largest value inside the fence; and 21.5 drawn on its own.
Quartiles and hinges, step by step
The line about position 5.75 goes fast, so let’s slow down. The 20 morning waits, sorted: 5.5, 6.5, 6.5, 7.5, 8, 8.5, 9, 9, 9.5, 10 | 10.5, 11, 11.5, 12, 12.5, 13, 14.5, 15.5, 16, 21.5 (the bar splits the two halves).
| What I compute | Calculation | Result | Why |
|---|---|---|---|
| position | it falls between the 5th (8) and the 6th (8.5), and moves .75 of the way | ||
| position | between the 15th (12.5) and the 16th (13), a quarter of the way | ||
| Hinges | and | 8.25 and 12.75 | fivenum takes the median of each half |
Both methods look at the same two values: the hinge stays right in the middle and quantile moves closer to one of them. That’s why they come out so similar.
Check you’ve got it: if you added one more wait of 10 minutes (21 values), what would be?
The position would be , a whole number: no interpolation needed. The 10 goes in higher up, so the 6th value is still 8.5, and .
Questions you might ask
Why do I name the vector overview? Because c(mean(x), median(x), ...) prints six numbers with no label and in the exam you would have to remember what each one was. With c(mean = ..., median = ...) the output reads by itself, and round keeps the names.
Why unname in the fences? quantile returns a number named "25%". When you subtract something from it, the name stays and the output says 25% above a fence that is not a quartile. It does not change the value, but it is confusing to read.
Why morning[-6] and not delete the value? The negative index drops element 6 only in that expression: the vector morning still has the 20 values. Removing odd data is a decision that has to be justified; to see how much they weigh, it is enough to compute without them.
Do I use quantile or fivenum for the quartiles? To give and , quantile (it is what summary, IQR and the exam use). fivenum is for understanding why the boxplot box does not end exactly at .
Is the 21.5 “bad”? No. A possible outlier is a value that does not follow the pattern of the rest, not a mistake. Here it is real (two full buses went past) and it tells something important about rush hour. If it were a recording mistake (210 instead of 21), then it would have to be corrected.
Computing the fences with the standard deviation (). The rule in the notes uses the quartiles and the , which the outlier itself cannot drag along.
Try it yourself
- Change the 21.5 to 31.5 and run it again: which measures change and which do not? (Hint: the median, , and the do not move.)
- Add the mean deviation,
MD = mean(abs(morning - mean(morning))), to theoverviewvector and compare it withs.
Program 2: the month’s frequency table, without losing any value
The second script puts together the 60 waits of the month and builds the complete frequency table (class, mark, absolute, relative and cumulative frequency) following the steps in the notes, computes the measures with the grouped data and compares them with those of the original data. Here is my mistake from the story, and its fix.
The idea
The steps from the notes, in R:
- Range and class length: the first integer larger than (
ceiling). - The breaks, starting a little below the minimum and with no value landing on a boundary.
cut+tablefor the frequencies, and a data frame with the complete table.- Grouped measures with the class marks, and a comparison with those of the data.
The important thing is to check that the frequencies add up to before carrying on.
Before programming, think about what happens to a value that lands exactly on a break. In R, (a, b] includes and excludes .
Put into words: you have to cover 28.5 minutes (the range) with 5 equal classes, 5.7 per class. You round up because rounding down falls short: 5 classes of 5 minutes from 2.5 end at 27.5 and the 31 would be left out. With 6, the five cover 30 minutes, 1.5 more than strictly needed: room to start a little below the minimum and end above the 31 (you’ll see they go from 2.25 to ).
The code
First, what I did wrong, so you can see how it is detected:
midday <- c(4.5, 6.0, 3.5, 7.0, 5.5, 2.5, 6.5, 4.0, 8.0, 5.0,
3.0, 7.5, 4.5, 6.0, 5.5, 9.0, 3.5, 5.0, 6.5, 4.0)
evening <- c(7.0, 10.5, 5.5, 12.0, 8.5, 31.0, 9.5, 6.5, 11.5, 7.5,
13.5, 8.0, 10.0, 6.0, 9.0, 12.5, 7.5, 14.0, 8.5, 10.5)
minutes <- c(morning, midday, evening) # the 60 waits of the month
c(n = length(minutes), min = min(minutes), max = max(minutes))
R <- max(minutes) - min(minutes) # range
c(R = R, R_over_5 = R / 5, length = ceiling(R / 5))
bad_breaks <- seq(min(minutes), by = 6, length.out = 6) # starting AT the minimum
bad_breaks
t_bad <- table(cut(minutes, bad_breaks))
t_bad
sum(t_bad) # 59, not 60!
table(cut(minutes, bad_breaks), useNA = "ifany") # the missing one is an NA
Output:
n min max
60.0 2.5 31.0
R R_over_5 length
28.5 5.7 6.0
[1] 2.5 8.5 14.5 20.5 26.5 32.5
(2.5,8.5] (8.5,14.5] (14.5,20.5] (20.5,26.5] (26.5,32.5]
33 22 2 1 1
[1] 59
(2.5,8.5] (8.5,14.5] (14.5,20.5] (20.5,26.5] (26.5,32.5]
33 22 2 1 1
<NA>
1
The range is ; divided by 5 classes it gives 5.7, so the length is 6. With the breaks at 2.5, 8.5, … the table looks right, but it adds up to 59. With useNA = "ifany" the culprit appears: an <NA>, the 2.5 from midday, which is not in (2.5, 8.5] because that class does not include its left end. And there is another hidden problem: 8.5 and 14.5 land exactly on a break (they go to the class on the left, but by hand you would hesitate).
The values that land on a break, one by one
| Value | Times | With bad_breaks | With breaks | Why |
|---|---|---|---|---|
| 2.5 | 1 | none (NA) | (2.25, 8.25] | (2.5, 8.5] does not include its left end |
| 8.5 | 3 | (2.5, 8.5] | (8.25, 14.25] | in the bad one it is the right end, which is included |
| 14.5 | 1 | (8.5, 14.5] | (14.25, 20.25] | the same, one class higher |
That’s why the bad table is not the good one minus one value: the three waits of 8.5 drop into the first class. It adds up: , and .
Now, done properly: the breaks start a quarter of a minute below the minimum (2.25), so no value, all of which go in half-minute steps, lands on a boundary:
breaks <- seq(2.25, by = 6, length.out = 6) # 2.25, 8.25, ..., 32.25
classes <- cut(minutes, breaks, dig.lab = 4) # dig.lab = 4: labels not trimmed
f <- table(classes)
sum(f) # now it is: 60
mark <- (head(breaks, -1) + tail(breaks, -1)) / 2 # midpoint of each class
freq_table <- data.frame(class = names(f), mark = mark, f = as.vector(f),
fr = round(as.vector(f) / 60, 3),
Fr = round(cumsum(as.vector(f)) / 60, 3))
freq_table
# Measures with the grouped data
fa <- as.vector(f); ng <- sum(fa)
mean_gr <- sum(fa * mark) / ng
s2_gr <- sum(fa * (mark - mean_gr)^2) / (ng - 1)
k <- which(cumsum(fa) >= ng / 2)[1] # median class
Fb <- sum(fa[seq_len(k - 1)]); L <- breaks[k]; w <- 6
M_gr <- L + w / fa[k] * (ng / 2 - Fb) # interpolated median
round(rbind(grouped = c(mean = mean_gr, var = s2_gr, median = M_gr),
original = c(mean(minutes), var(minutes), median(minutes))), 2)
hist(minutes, breaks = breaks, main = "Waits of the month", xlab = "Minutes")
Output
[1] 60
class mark f fr Fr
1 (2.25,8.25] 5.25 31 0.517 0.517
2 (8.25,14.25] 11.25 24 0.400 0.917
3 (14.25,20.25] 17.25 3 0.050 0.967
4 (20.25,26.25] 23.25 1 0.017 0.983
5 (26.25,32.25] 29.25 1 0.017 1.000
mean var median
grouped 8.95 23.30 8.06
original 8.90 21.69 8.00
How to read it
sum(f)gives 60: nothing has been lost.- The table: 31 waits (51.7%) between 2.25 and 8.25 minutes, 24 (40%) between 8.25 and 14.25, and only 5 above 14.25. The
Frcolumn says that 91.7% of the time I waited 14.25 minutes or less. dig.lab = 4is there so the labels come out whole. Without it, R trims them to 3 digits and writes(8.25,14.2], which looks like a different class from the real one. If you see strange labels in acuttable, this is it.- The median class is the first (
kis 1): it already accumulates 31 values and . Since there are no classes before it, and . - The comparison, in two rows: with the table, mean 8.95, variance 23.30 and median 8.06; with the data, 8.90, 21.69 and 8. They are close, and the differences come from assuming each value is worth its mark: the evening 31 becomes 29.25 and the midday 2.5-3.5 become 5.25.
The histogram (in the drawing) has all the classes the same width, so here the height is the frequency. Peak in the first class, a second one almost as tall and a tail to the right with three nearly empty classes: the shape of waits that are almost always short and sometimes get very long.
The grouped mean and variance, class by class
mean_gr does in one line what by hand is this table: each class counts as if its waits were all worth its mark.
| Mark | f | f · mark | f · (mark − 8.95)² |
|---|---|---|---|
| 5.25 | 31 | 162.75 | 424.39 |
| 11.25 | 24 | 270 | 126.96 |
| 17.25 | 3 | 51.75 | 206.67 |
| 23.25 | 1 | 23.25 | 204.49 |
| 29.25 | 1 | 29.25 | 412.09 |
| Sum | 60 | 537 | 1374.6 |
Mean: . Variance: (divided by , like var()). The two waits in classes 4 and 5 contribute 616.58 of the 1374.6, 45%, while being 2 values out of 60: the histogram’s long tail, in numbers.
Check you’ve got it: what is with the grouped data, and why doesn’t it look like the one from quantile?
You are looking for value number . The cumulative frequency is 31 after the first class and 55 after the second, so it is in the second: . quantile(minutes, 0.75) gives 10.63. The formula assumes the 24 waits of the class are spread evenly, and they are not: 15 fall in the lower half (up to 11.25).
Questions you might ask
Why seq(2.25, by = 6, length.out = 6) and not seq(2.25, 32.25, by = 6)? They give the same here; with length.out you make sure you get exactly 6 breaks (5 classes) even if you change the start. With to and by, if the end does not fall on the sequence, you end up one break short and the maximum outside.
And if I prefer to cut at 2.5 and let the minimum in? You can, with cut(minutes, bad_breaks, include.lowest = TRUE): the first class becomes [2.5, 8.5]. But 8.5 and 14.5 would still land on the breaks; what the notes say (no value should coincide with a boundary) is cleaner.
How does the code know which is the median class? cumsum(fa) >= ng / 2 gives TRUE for the classes whose cumulative count reaches half the data, and which(...)[1] keeps the first one. It is the same as what you do by hand by looking at the cumulative column.
Why seq_len(k - 1) and not 1:(k - 1)? Because when , 1:0 is the vector c(1, 0) and it would add the first class. seq_len(0) is an empty vector and its sum is 0, which is right: there are no classes before the first.
Is the grouped mean “worse”? It is an approximation: it is the best you can do when you only have the table. If you have the data, use the data.
Not checking sum(table(...)). If it adds up to less than , some value has been left outside the classes (below the first break, above the last one or exactly on the first break).
Try it yourself
- Repeat the table with 6 classes of length 5 starting at 2.25. Does the grouped mean change much?
- Draw the histogram with
breaks = c(2.25, 5.25, 8.25, 11.25, 14.25, 32.25)(the last class wide) and look at the vertical axis: why does it no longer sayFrequency?
Program 3: comparing the three time slots
The third script puts the 60 waits into a data frame with their time slot and whether the bus arrived full, compares the slots (measures and side-by-side boxplots) and checks with real data the formula for the variance of several groups from proof 6.
The idea
In a data frame, each row is a wait and each column a variable. With tapply(variable, group, function) you apply a function to each group in one go, and with boxplot(variable ~ group) you draw one boxplot per group. For the categorical variable (full), the two-way table and its row proportions.
Before programming, think about what you expect to see: a quiet midday, morning and evening with longer waits. If the result contradicts what you expected, check the data before the theory.
The underlying question, in words: does the time I go change how long I wait? The formula from proof 6 splits the variation in two: “within” measures how far the waits are from the mean of their own slot, and “between”, how far the slot means are from the month’s. Added together and divided by , they give the var() of the 60.
The code
waits <- data.frame(
slot = rep(c("morning", "midday", "evening"), each = 20),
minutes = minutes,
full = c(rep("yes", 11), rep("no", 9), # morning: 11 full
rep("yes", 3), rep("no", 17), # midday: 3
rep("yes", 7), rep("no", 13))) # evening: 7
str(waits)
# factor in the order of the day (otherwise R sorts them alphabetically)
waits$slot <- factor(waits$slot, levels = c("morning", "midday", "evening"))
round(tapply(waits$minutes, waits$slot, mean), 2) # mean per slot
round(tapply(waits$minutes, waits$slot, sd), 2) # sd per slot
aggregate(minutes ~ slot, data = waits, FUN = median) # median per slot
# The variance of everything, from the summaries of each group
nj <- tapply(waits$minutes, waits$slot, length)
mj <- tapply(waits$minutes, waits$slot, mean)
vj <- tapply(waits$minutes, waits$slot, var)
xbar <- sum(nj * mj) / sum(nj)
s2 <- (sum((nj - 1) * vj) + sum(nj * (mj - xbar)^2)) / (sum(nj) - 1)
round(c(mean_groups = xbar, mean_all = mean(waits$minutes),
var_groups = s2, var_all = var(waits$minutes)), 2)
round(c(within = sum((nj - 1) * vj), between = sum(nj * (mj - xbar)^2)), 2)
# The categorical variable: did it arrive full?
tf <- table(waits$slot, waits$full)
tf
round(prop.table(tf, margin = 1), 2) # row proportions (per slot)
boxplot(minutes ~ slot, data = waits, ylab = "Minutes waited")
barplot(t(tf), beside = TRUE, legend.text = TRUE, ylab = "Number of buses")
Output
'data.frame': 60 obs. of 3 variables:
$ slot : chr "morning" "morning" "morning" "morning" ...
$ minutes: num 8.5 12 6.5 14.5 9 21.5 7.5 11 10.5 13 ...
$ full : chr "yes" "yes" "yes" "yes" ...
morning midday evening
10.90 5.35 10.45
morning midday evening
3.87 1.73 5.42
slot minutes
1 morning 10.25
2 midday 5.25
3 evening 9.25
mean_groups mean_all var_groups var_all
8.90 8.90 21.69 21.69
within between
899.8 380.1
no yes
morning 9 11
midday 17 3
evening 13 7
no yes
morning 0.45 0.55
midday 0.85 0.15
evening 0.65 0.35
How to read it
strsays there are 60 rows and 3 columns:slotandfullare text (chr) andminutesis a number (num). Afterwards we turnslotinto a factor to fix the order of the slots in the tables and the plots.- Means per slot: morning 10.9, midday 5.35 and evening 10.45. At midday I wait half as long as at rush hour.
- Standard deviations: 3.87, 1.73 and 5.42. Midday is not only shorter, it is more regular. The evening has the largest deviation, because of the 31 (the bus that never came).
- Medians (with
aggregate, which returns a data frame): 10.25, 5.25 and 9.25. In the evening the median is 1.2 minutes below the mean: the 31 pulls the mean up. - The check of proof 6: with the summaries of the three groups you get a mean of 8.9 and a variance of 21.69, the same as with the 60 waits. And the split: the sum of squares within the groups is 899.8 and between groups, 380.1. Almost 30% of all the month’s variability () is explained just by the time I go.
- The
fulltable: in the morning, 11 out of 20 buses arrived full; at midday, 3; in the evening, 7. Withmargin = 1each row adds up to 1: 55% of mornings, 15% of middays and 35% of evenings. Withoutmargin, the proportions would be over the 60 and the slots could not be compared.
The three boxplots together, in the drawing, tell it at a glance: the midday box is lower and narrower; the morning and evening boxes overlap almost entirely, and each has its loose point (21.5 and 31).
The barplot with beside = TRUE puts the two bars of each slot side by side, with the legend that legend.text = TRUE asks for. You read it pair by pair: only in the morning is the “yes” bar taller than the “no” bar (11 against 9), at midday there are hardly any full buses (3 out of 20) and the evening sits in between (7 out of 20). They are the same counts as tf, but the drawing shows at a glance that the morning rush hour is the worst.
Within and between, slot by slot
899.8 and 380.1 come from adding one piece per slot, with :
| Slot | Within: | Between: | |||
|---|---|---|---|---|---|
| morning | 20 | 10.9 | 14.99 | 284.8 | |
| midday | 20 | 5.35 | 3.00 | 57.05 | |
| evening | 20 | 10.45 | 29.37 | 557.95 | |
| Sum | 60 | 899.8 | 380.1 |
And . Midday adds almost nothing to “within”, but puts in 252.05 of the 380.1 of “between”: its mean is the furthest away. The evening puts in 557.95 of “within”, mostly because of the 31.
What would happen if I removed the 31 from the evening? Would the slot explain more or less of the variability?
Before running it: the 31 is far from the evening mean, so it weighs mostly on “within”. Without it, “within” should drop a lot.
no31 <- minutes[-46] # the 31 is value 6 of the evening: 40 + 6 = 46
slot <- rep(c("morning", "midday", "evening"), times = c(20, 20, 19)) # the evening now has 19
nj <- tapply(no31, slot, length)
mj <- tapply(no31, slot, mean)
vj <- tapply(no31, slot, var)
xbar <- sum(nj * mj) / sum(nj) # weighted: the groups are no longer equal
round(c(mean = xbar, within = sum((nj - 1) * vj), between = sum(nj * (mj - xbar)^2)), 2)
round(sum(nj * (mj - xbar)^2) / sum((no31 - xbar)^2), 2) # share explained by the slot
Output:
mean within between 8.53 455.27 327.94 [1] 0.42
“Within” drops from 899.8 to 455.27, almost half, because of a single value; “between” drops less (to 327.94), because the evening mean moves closer to the month’s. The slot goes from explaining 30% to 42%: before concluding, check how much the odd value weighs.
Questions you might ask
Why do I turn slot into a factor? Because R sorts text alphabetically, and “evening, midday, morning” is not the order of the day. With factor(..., levels = ...) you decide the order and tapply, table and boxplot respect it.
tapply or aggregate? They do the same. tapply returns a named vector (handy for further calculations, as here with nj, mj and vj); aggregate returns a data frame (handy for reading or exporting).
Why prop.table(tf, margin = 1)? Because the question is “what proportion of buses arrive full in each slot?”, and for that each row has to add up to 1. With margin = 2 each column would add up to 1 and you would be answering a different question: “of the full buses, how many are from each slot?”.
Why is the “between” sum of squares so large? Because the slot means are far apart (5.35 against 10.9). If the three slots had the same mean, “between” would be 0 and all the variability would be “within”.
What does t(tf) do in the barplot? It transposes the table so the bars are grouped by slot (a yes/no pair in each slot). Without t, they would be grouped by “yes” and “no”.
Taking the mean of the three means, , and calling it “the month’s mean”. Here it matches (8.9) only because the three slots have 20 waits each. With groups of different sizes, you must weight by .
Try it yourself
- Add a fourth slot,
"night", with 10 made-up waits between 12 and 25 minutes, and repeat the check of the variance of several groups (now the groups are not the same size). - Draw
pie(table(waits$full))and compare it with thebarplot: which one lets you compare the slots better?
Common mistakes in this practice
- Starting the
cutbreaks at the minimum. The smallest value is left out (it becomes anNA) and the table adds up to . Start a little below or useinclude.lowest = TRUE. - Not checking that the frequencies add up to . It is one line,
sum(table(...)), and it stops the error from spreading to every grouped measure. - Misreading the
cutlabels.(8.25,14.2]is(8.25,14.25]trimmed to 3 digits: usedig.lab. - Comparing slots with proportions over the total. To compare groups, row proportions (
margin = 1). - Computing the fences with the mean and the standard deviation. The rule uses , and the .
- Averaging the means of groups of different sizes without weighting. The overall mean is .
Try it in the R playground
Open the R playground and paste this script, which puts together the essentials of the three programs:
morning <- c(8.5, 12.0, 6.5, 14.5, 9.0, 21.5, 7.5, 11.0, 10.5, 13.0,
5.5, 9.5, 16.0, 8.0, 12.5, 6.5, 10.0, 15.5, 9.0, 11.5)
midday <- c(4.5, 6.0, 3.5, 7.0, 5.5, 2.5, 6.5, 4.0, 8.0, 5.0,
3.0, 7.5, 4.5, 6.0, 5.5, 9.0, 3.5, 5.0, 6.5, 4.0)
evening <- c(7.0, 10.5, 5.5, 12.0, 8.5, 31.0, 9.5, 6.5, 11.5, 7.5,
13.5, 8.0, 10.0, 6.0, 9.0, 12.5, 7.5, 14.0, 8.5, 10.5)
waits <- data.frame(slot = factor(rep(c("morning", "midday", "evening"), each = 20),
levels = c("morning", "midday", "evening")),
minutes = c(morning, midday, evening))
View(waits)
table(cut(waits$minutes, seq(2.5, by = 6, length.out = 6)), useNA = "ifany")
table(cut(waits$minutes, seq(2.25, by = 6, length.out = 6), dig.lab = 4))
boxplot(minutes ~ slot, data = waits)
What to look at:
View(waits)opens the table in a tab: sort it byminutesby clicking on the header and look for the 2.5 and the 31.- The two
cuttables: the<NA>shows up in the first one; not in the second. - In the Environment tab,
waitssays “60 obs. of 2 variables”. - In Plots, the three boxplots: switch to
boxplot(minutes ~ slot, data = waits, horizontal = TRUE)and compare which one reads better.
Summary
round(c(mean = ..., s = ...), 2)gives a named summary with the exam’s decimals.- Possible outliers are found with the fences and , and their weight is measured by repeating the summary without them.
- In a frequency table, the breaks start below the minimum and you always check that
sum(table(...))is . - Grouped measures are close to the data ones, but not equal: you have to compare them and explain why.
tapply,aggregateandboxplot(y ~ group)compare groups;prop.table(..., margin = 1), proportions within each group.- The variance of several groups splits into “within” and “between”, and with real data it matches
var()exactly.
Checklist: have you practised it?
- Have you run the three programs and checked the outputs?
- Can you explain why the first table added up to 59?
- Can you compute the grouped median by hand from the cumulative column?
- Could you say which slot has the most regular waits and with which number you justify it?
- Have you tried the “Try it yourself” tasks without looking at the theory?
- Have you saved these scripts in your
.Rfile for the exam?
If you answered yes to almost everything, you are ready for the descriptive statistics exercises, where I no longer give you the code: they are EC1-style questions, with their marks. See you there!
Next step: exercisesDescriptive statistics — ME1 exam-style exercises with the campus bus: tables with cut, the interpolated median and the variance of several groups (and the median that escaped from its class)Did this article help you? Here is how you can support SergioLearns →



