R intensive 1: descriptive statistics — exercises with the flat’s grocery receipts, your own summ() function and well-labelled plots (and the NA that ate the whole month)
In my first month in a shared flat we logged every grocery receipt in a sheet, and at the end I wrote my first R function to summarise it all: it returned NA in every single box. One receipt without an amount, the one from the 18th, was enough to blank out the mean, the quartiles and the standard deviation, because I had not decided what to do with missing data.
This article is the hands-on part of block 1 of the R intensive. The theory, with every piece explained, is in R intensive 1: descriptive statistics; here I no longer hand you the code. The statistics (mean, quartiles, coefficient of variation, outliers with the 1.5·IQR rule) are taken as known: if something sounds odd, review it in the ME1 descriptive statistics exercises. What you practice here is programming it yourself: writing the function, grouping with tapply and aggregate, and drawing plots that make sense without explaining them.
Table of Contents
How to use this article
- Open the R playground (or RStudio) and paste the data from the next section. Every exercise uses the same table.
- Try each level before looking at the solution. Level 1 is reproducing and reading outputs; level 2, writing the function; level 3, a full problem in the format of the ME1 exam script (chained parts and indicative points).
- The solutions are folded. Open them when you have something to compare: each one explains why it is written that way and what would have gone wrong with the obvious alternative.
- Finish with the 10-question test on reading code and copy the “For your script” section into your
.Rfile: it is the block’s code, commented and without problem statements, like the one you can take into the exam.
In the ME1 exam results are given to 2 decimal places. Get used to ending your calculations with round(…, 2) or to passing digits = 2 to your functions.
The data: October’s receipts
Four flatmates (Laura, Sergio, Dani and Marta) log every shop in a table: the day, who paid, which shop (the corner shop, the big supermarket or the online order) and the amount in euros. The data are made up, but they have what a real table has: small everyday shops, big weekly shops, one receipt with no amount (the one from the 18th) and a party shop that stands out from everything else.
# October's 40 receipts (amount in euros; NA = receipt without an amount)
receipts <- data.frame(
day = c(1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 15,
16, 17, 18, 18, 19, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31),
who = c("Laura", "Sergio", "Dani", "Marta", "Laura", "Dani", "Sergio", "Marta", "Laura", "Dani",
"Sergio", "Marta", "Laura", "Sergio", "Dani", "Marta", "Laura", "Sergio", "Dani", "Marta",
"Laura", "Sergio", "Dani", "Marta", "Laura", "Sergio", "Dani", "Marta", "Laura", "Sergio",
"Dani", "Marta", "Laura", "Sergio", "Dani", "Marta", "Laura", "Sergio", "Dani", "Marta"),
shop = c("Market", "Corner", "Corner", "Market", "Online", "Corner", "Corner", "Market", "Corner", "Market",
"Corner", "Online", "Market", "Corner", "Corner", "Market", "Corner", "Market", "Corner", "Online",
"Market", "Corner", "Corner", "Market", "Corner", "Corner", "Market", "Corner", "Online", "Corner",
"Corner", "Market", "Corner", "Market", "Corner", "Online", "Corner", "Corner", "Market", "Market"),
spend = c(42.80, 9.35, 14.20, 51.60, 38.90, 7.45, 12.10, 47.25, 11.60, 55.30,
8.90, 36.40, 49.75, 13.25, 6.80, 44.10, 10.95, 58.20, 15.40, 41.15,
46.30, 7.95, NA, 53.80, 12.45, 9.60, 96.40, 11.20, 39.70, 14.85,
8.25, 48.90, 10.30, 52.45, 13.70, 37.85, 9.15, 12.60, 45.50, 50.20)
)
str(receipts)
Output:
'data.frame': 40 obs. of 4 variables: $ day : num 1 1 2 3 4 4 5 6 7 8 ... $ who : chr "Laura" "Sergio" "Dani" "Marta" ... $ shop : chr "Market" "Corner" "Corner" "Market" ... $ spend: num 42.8 9.35 14.2 51.6 38.9 ...
str() is always the first thing to look at: 40 rows, 4 columns, who and shop are text (chr) and spend is a number (num). If spend had come out as chr, no numeric function would work (you will see it in “What’s wrong here?”).
Level 1: reproduce and read the outputs
Type (do not copy) these four commands and, before running them, write down what you expect. Then answer the questions with the output in front of you.
table(receipts$shop)
round(tapply(receipts$spend, receipts$who, sum, na.rm = TRUE), 2)
aggregate(spend ~ shop, data = receipts, FUN = mean)
hist(receipts$spend, breaks = seq(0, 100, by = 10),
main = "Grocery receipts in October", xlab = "Amount (euros)", ylab = "Number of receipts",
col = "lightblue")
Questions:
- How many receipts are there from each shop? Do they add up to 40?
- Who paid the most over the month, and how much? What would happen without
na.rm = TRUE? aggregategives the corner shop’s mean with 20 receipts, buttablecounted 21. Where is the missing one?- In the histogram, why are there two hills with a gap between them? What is the lonely bar on the right?
tapply(x, group, FUN) splits x by group and applies FUN to each piece; whatever you write after FUN (here na.rm = TRUE) is passed on to that function. aggregate with a formula (spend ~ shop) does the same but returns a data frame and drops the rows with NA before grouping.
Level 2: write your own summary function
Write a function summ(x, digits = 2) that takes a numeric vector and returns a named vector with these eight values: n (valid data), mean, Q1, median, Q3, sd, CV (coefficient of variation in %) and outliers (how many data points fall outside the fences and ). Conditions:
- If
xis not numeric or is empty, the function stops with a clear error (stopifnot). - If there are
NAvalues, it removes them and says how many withmessage(); it does not keep quiet about them. - Everything rounded to
digitsdecimal places.
(We call it summ and not summary so as not to hide R’s own summary().) Expected result with the receipts:
> summ(receipts$spend)
Note: removing 1 NA value(s)
n mean Q1 median Q3 sd CV
39.00 29.66 11.07 15.40 46.77 21.42 72.24
outliers
0.00
quantile(x, c(0.25, 0.5, 0.75), names = FALSE) gives you the three quartiles at once and without names (so you do not drag “25%” into the final vector). To count outliers, sum a logical vector: sum(x < a | x > b) counts the TRUEs.
Level 3 (challenge): the flat’s report, in the exam format
Exercise (15 points). The four flatmates want to settle October’s accounts with an R script they can run again in November. Use the receipts table and your summ() function from level 2.
- a) (3 points) Check how many receipts have no amount and who paid them. Create
valid, the table without those rows, and say how many rows it has. - b) (4 points) Apply
summ()to the spend of each shop with a single command and store the result in a matrixshop_table(one column per shop). Which shop has the most homogeneous spend according to the CV? Does any have outlying receipts? - c) (4 points) Draw a box plot of the spend by shop with a title, labelled axes and the three shops in the order Corner, Market, Online. Write the code that pulls out the amount, the day and who paid the outlying receipt or receipts.
- d) (4 points) Write a function
settle(spend, who)that returns, for each person, how much they are owed (positive) or owe (negative) so that everyone pays the same, rounded to 2 decimal places and checking that the balances add up to 0. Draw the balances in a bar chart.
For part b, split(x, group) turns the vector into a list with one piece per shop, and sapply(list, summ) applies the function to each piece and binds the results as columns. For part c, boxplot(…, plot = FALSE) returns the outliers in $out and which group they belong to in $group.
Solutions
Level 1
The approach, before running anything. First, what shape each output will have. table counts rows: one number per shop, and they must add up to 40. tapply splits the spend by person and sums each piece: four numbers. aggregate does the same by shop, but returns a table. If you know what you expect, anything odd jumps out.
With the missing receipt, the obvious path is to think aggregate got it wrong. The right one is to ask what each function does with the NA: table counts the row even if it has no amount, and aggregate drops it before grouping.
See the level 1 solution
table(receipts$shop) round(tapply(receipts$spend, receipts$who, sum, na.rm = TRUE), 2) aggregate(spend ~ shop, data = receipts, FUN = mean)
Output:
Corner Market Online
21 14 5
Dani Laura Marta Sergio
263.00 271.90 422.45 199.25
shop spend
1 Corner 11.00250
2 Market 53.03929
3 Online 38.80000
- Receipts per shop: 21 from the corner shop, 14 from the big supermarket and 5 online; 21 + 14 + 5 = 40, all of them.
tablecounts rows, whether or not they have an amount. - Who paid the most: Marta, 422.45 €; the least, Sergio, 199.25 €. Without
na.rm = TRUE, Dani’s sum would beNA, because the receipt with no amount is his (the 18th), and the other three would still be fine: the NA only contaminates the group it is in. - The missing receipt: it is that very one, from the 18th, which was from the corner shop.
aggregatewith a formula usesna.action = na.omitby default and drops the row before grouping, so the corner shop is left with 20. It is not a bug, but you need to know it: if you compare thenfromtablewith the one fromaggregate, they do not match. - The histogram:
hist(receipts$spend, breaks = seq(0, 100, by = 10),
main = "Grocery receipts in October", xlab = "Amount (euros)", ylab = "Number of receipts",
col = "lightblue")
In the plot there are two kinds of shop: the everyday one, from 0 to 20 €, with 20 receipts (8 + 12), and the weekly one, from 30 to 60 €, with 18 (4 + 8 + 6). Between 20 and 30 there are none: nobody does a “medium” shop. The lonely bar from 90 to 100 is the party shop on the 21st (96.40 €). Look at the labels: without main, xlab and ylab, R would have written “Histogram of receipts$spend” and “Frequency”, which say nothing to someone who has not seen the code.
With breaks = seq(0, 100, by = 10) you choose the breaks. If you let R choose them, they change with the data and two histograms of two months cannot be compared.
Check you’ve got it: what comes out of aggregate(spend ~ who, data = receipts, FUN = sum)? Do you need na.rm = TRUE?
The same four sums as with tapply, but in a table:
who spend 1 Dani 263.00 2 Laura 271.90 3 Marta 422.45 4 Sergio 199.25
You don’t need na.rm = TRUE: the formula already dropped the row from the 18th before grouping, so sum gets Dani’s receipts without the NA. With tapply, the NA does reach sum, and that is why there you have to tell it to ignore it.
Level 2
The approach, before the code. Decide the order first: check the input, remove the NAs, quartiles, fences, result and rounding. Why the NAs so early? Because everything after them hates them: quantile with an NA stops with “missing values and NaN’s not allowed if ‘na.rm’ is FALSE”, and mean returns NA without complaining, which is worse.
The obvious alternative would be to put na.rm = TRUE in quantile, mean and sd. That is three places to remember, and length(x) would still count the NA: your n would say 40 instead of 39. Cleaning once, at the start, fixes all of it.
See the level 2 solution
# summ(): eight numbers that describe a vector, with 'digits' decimal places
summ <- function(x, digits = 2) {
# 1. Check the input: if it is not a number or is empty, stop with a clear error
stopifnot(is.numeric(x), length(x) > 0)
# 2. The NAs: remove them, but say so (never silently)
missing <- sum(is.na(x))
if (missing > 0) {
message("Note: removing ", missing, " NA value(s)")
x <- x[!is.na(x)]
}
# 3. Quartiles without names (names = FALSE) so as not to drag "25%" into the result
q <- quantile(x, c(0.25, 0.5, 0.75), names = FALSE)
iqr <- q[3] - q[1]
# 4. Outliers: those outside the fences Q1 - 1.5 IQR and Q3 + 1.5 IQR
outl <- sum(x < q[1] - 1.5 * iqr | x > q[3] + 1.5 * iqr)
# 5. The result: a named, rounded vector. It is the last expression: it is what gets returned
round(c(n = length(x), mean = mean(x), Q1 = q[1], median = q[2], Q3 = q[3],
sd = sd(x), CV = sd(x) / mean(x) * 100, outliers = outl), digits)
}
summ(receipts$spend)
Output:
Note: removing 1 NA value(s)
n mean Q1 median Q3 sd CV
39.00 29.66 11.07 15.40 46.77 21.42 72.24
outliers
0.00
Why it is written this way:
stopifnotat the start. If someone passes itreceipts$who(text), the function stops on the first line with “is.numeric(x) is not TRUE”, instead of throwing a strange error fromquantilefive lines further down. Checking the input where it comes in is what makes a function reusable.messageand notprintorcat.messagegoes through the notes channel: you see it in the console, but it is not part of the result and it can be silenced withsuppressMessages(). Hiding the NAs (withna.rm = TRUEin every function) would give the same number, but you would not know a receipt was missing; the story at the start is the version with nothing at all: NA everywhere.- A single
roundat the end. If you round the quartiles before working out the IQR, you carry the rounding error into the fences. Compute with all the decimals and round once, when returning. - The named vector.
summ(x)["CV"]gives you the coefficient of variation by name, without remembering it was the seventh. - No
return(). In R, a function returns its last expression.return()is needed to leave early (for example, inside anif); at the end it is optional. What cannot happen is for the last line to be an assignment (you will see it in “What’s wrong here?”).
How to read the output: 39 valid receipts (40 minus the NA), a mean of 29.66 € but a median of 15.40 €. The mean is well above the median because the big shops pull it up; and the CV of 72.24 % says the amount of a receipt varies a lot, which we already saw in the two hills of the histogram. No outliers in the whole set: with such a big IQR (46.77 − 11.07 = 35.70), the upper fence is at 46.77 + 1.5 · 35.70 = 100.32 €, and not even the party gets there.
Check you’ve got it: what does summ(c(5, NA, NA)) return?
First the note, “removing 2 NA value(s)”, and then:
n mean Q1 median Q3 sd CV outliers
1 5 5 5 5 NA NA 0
Only one value is left, the 5: mean, quartiles and median are all 5, and the IQR is 0, so there are no outliers. The sd comes out NA because it divides by n − 1 = 0: with one value there is no spread to measure. The CV inherits it. It isn’t a bug in your function; it’s statistics.
Level 3
The approach, part by part. What you decide in a) you carry all the way to d): think the four through before writing code.
- a) Decide once what to do with the NA. From here on everything works with
valid, and no part trips over the receipt from the 18th again. - b) One command for the three shops, not three. The obvious path is to call
summ()three times, filtering withvalid$shop == "Corner". If a fourth shop appears in November, those lines don’t see it.splitmakes one piece for every shop in the data. And to compare, the CV: the sd says the big supermarket varies about five times more than the corner shop (13.22 € against 2.55 €), but only because its shops are five times bigger; in proportion, almost the same (24.92 % against 23.14 %). - c) Let the code find the outlier, not your eyes. Reading “96.40” off the plot and filtering it by hand works today and fails in November.
box$outis exactly whatboxplotdecided to draw as an outlier. - d) The calculation in words before R. Each person has paid something; everyone should have paid a quarter of the total (1156.60 / 4 = 289.15 €); the balance is the difference. In R:
tapply,mean(paid)and a subtraction.
Subtracting mean(valid$spend), 29.66 €, which is what one receipt costs, not each person’s share. The balances all come out positive and add up to 1037.96 €. The stopifnot at the end is there to catch exactly this.
And why abs(sum(balance)) < 0.05 and not sum(balance) == 0? Because the computer stores decimals with a tiny error: here sum(balance) gives 7.1 · 10⁻¹⁵, not 0, and == would reject a calculation that is right.
See the level 3 solution
a) Receipts without an amount (3 points).
# ==== Exercise 3a: receipts without an amount ====
no_amount <- is.na(receipts$spend) # logical vector: TRUE where the amount is missing
sum(no_amount) # how many there are
receipts[no_amount, c("day", "who", "shop")]
valid <- receipts[!no_amount, ] # the table without those rows
nrow(valid)
Output:
[1] 1 day who shop 23 18 Dani Corner [1] 39
One receipt without an amount, Dani’s on the 18th at the corner shop; valid has 39 rows. Storing the logical vector in no_amount instead of writing is.na(receipts$spend) three times means that, if the condition changes in November (amounts of 0, for example), only one line needs touching.
How it is marked (indicative, my own, not official). 1 point for detecting the NA with is.na and saying whose it is, 1 for creating valid without losing columns (the comma in receipts[!no_amount, ]) and 1 for the number of rows.
b) summ() per shop (4 points).
# ==== Exercise 3b: summ() for each shop ==== shop_table <- sapply(split(valid$spend, valid$shop), summ) shop_table names(which.min(shop_table["CV", ])) # the shop with the smallest CV
Output:
Corner Market Online n 20.00 14.00 5.00 mean 11.00 53.04 38.80 Q1 9.09 46.54 37.85 median 11.07 49.98 38.90 Q3 12.76 53.46 39.70 sd 2.55 13.22 1.80 CV 23.14 24.92 4.65 outliers 0.00 1.00 0.00 [1] "Online"
split gives a list with three vectors (Corner, Market, Online) and sapply applies summ to each one and binds the three results as columns: an 8 × 3 matrix. As valid no longer has NAs, the note does not appear. The most homogeneous spend is online (CV of 4.65 %): the five orders go from 36.40 to 41.15 €, nearly always the same basket. The corner shop and the big supermarket have a similar CV (23.14 % and 24.92 %), and the big supermarket has an outlier: with the 1.5·IQR rule inside its group, the party shop does stand out (in the whole set it did not, because there the IQR was huge).
Comparing the sds of the shops as they are and saying “the corner shop is much more homogeneous than the big supermarket, because its sd is five times smaller (2.55 against 13.22)”. The standard deviation is in euros and depends on the size of the shops; to compare the spread of groups with such different means (11 € against 53 €) you use the CV, which has no units: in proportion to their means, they hardly differ (23.14 % against 24.92 %).
c) Box plot and the outlying receipt (4 points).
# ==== Exercise 3c: box plot by shop ====
valid$shop <- factor(valid$shop, levels = c("Corner", "Market", "Online"))
box <- boxplot(spend ~ shop, data = valid,
main = "Spend per receipt by shop (October)",
xlab = "Shop", ylab = "Receipt amount (euros)",
col = c("lightblue", "orange", "lightgreen"))
box$out # amount of the outliers
valid[valid$spend %in% box$out, c("day", "who", "shop", "spend")]
Output:
[1] 96.4 day who shop spend 27 21 Dani Market 96.4
In the plot, the corner shop’s box sits low and is narrow (from 9.03 to 12.93 €, the middle half of the everyday shops; boxplot uses Tukey’s hinges, which is why they do not match the Q1 and Q3 from quantile, 9.09 and 12.76, to the cent), the big supermarket’s box sits high (from 46.30 to 53.80 €) and the online one is almost a line. The loose point above the big supermarket is the 96.40 € receipt: on the 21st, Dani’s. Besides drawing, boxplot returns a list with the numbers behind the plot: $out holds the outliers, and %in% finds their rows in the table. It is better than searching for “96.4” by hand, because the code still works in November with other data.
The order of the boxes is decided by the factor levels. With factor(…, levels = c(…)) you choose the order; otherwise R sorts them alphabetically (which happened to match here, but in another table it would not).
d) The settle() function and its bars (4 points).
# ==== Exercise 3d: how much each person owes or is owed ====
settle <- function(spend, who) {
stopifnot(is.numeric(spend), length(spend) == length(who))
paid <- tapply(spend, who, sum, na.rm = TRUE) # what each person has paid
balance <- round(paid - mean(paid), 2) # positive: owed to them; negative: they owe
stopifnot(abs(sum(balance)) < 0.05) # the balances must add up to 0 (bar cents)
balance
}
balances <- settle(valid$spend, valid$who)
balances
barplot(balances, main = "Balance of each flatmate in October",
ylab = "Euros (positive: owed to them)", col = ifelse(balances > 0, "darkgreen", "firebrick"))
abline(h = 0)
Output:
Dani Laura Marta Sergio -26.15 -17.25 133.30 -89.90
Each person should have paid the average of what the four paid: (263.00 + 271.90 + 422.45 + 199.25) / 4 = 289.15 €. Marta paid 133.30 € too much (green bar upwards: she is owed that), and Sergio, Dani and Laura owe 89.90, 26.15 and 17.25 €. Check: 133.30 − 89.90 − 26.15 − 17.25 = 0. That sum is what the second stopifnot looks at: if it ever does not add up, the rounding or the data have a problem, and you would rather find out before sending the bill to the group chat.
How it is marked (indicative, my own, not official). b: 2 points for the matrix with a single command and 2 for choosing the CV with its reason. c: 2 for the plot with title, axes and order, 2 for pulling out the outlier’s row with code. d: 2 for the function with its check, 1 for the balances and 1 for the bars.
Check you’ve got it: if Ana moved in in November and didn’t pay a single receipt, would she show up in the balances from settle()?
No. tapply only makes groups for the names that appear in who, and Ana isn’t on any receipt. The serious part is that the share would still be split four ways.
The fix: turn who into a factor with the five names as levels and add default = 0 to tapply, so the empty group sums to 0 and not NA. With October’s data, the share would drop to 1156.60 / 5 = 231.32 €, which is exactly what Ana would owe.
What’s wrong here?
Three snippets with a very common bug. Predict what comes out before reading the output.
Snippet 1. A function for the coefficient of variation.
cv <- function(x) {
result <- sd(x) / mean(x) * 100
}
cv(c(10, 12, 14))
Nothing comes out. The function does calculate (the CV is 16.67 %), but its last expression is an assignment, and an assignment returns its value invisibly: the console does not print it. If you do v <- cv(c(10, 12, 14)), v is 16.67; the problem only shows when you call it on its own, which is exactly how you test it.
Ending a function with result <- …. Fix: make the last line the value (result on its own, or the calculation without assigning).
cv <- function(x) {
result <- sd(x) / mean(x) * 100
result
}
round(cv(c(10, 12, 14)), 2)
Output:
[1] 16.67
Snippet 2. Removing the NA and summing per person.
s <- na.omit(receipts$spend) tapply(s, receipts$who, sum)
Output:
Error in tapply(s, receipts$who, sum) : arguments must have same length
na.omit removed the NA from s, which now has 39 elements, but receipts$who still has 40. tapply pairs element 1 with 1, 2 with 2…, and with different lengths it does not know whom to give each amount to. Removing NAs from a single column misaligns the table.
Cleaning a loose vector and carrying on with the other columns uncleaned. Fix: filter rows of the table (valid <- receipts[!is.na(receipts$spend), ]) or let the function handle it (na.rm = TRUE).
tapply(receipts$spend, receipts$who, sum, na.rm = TRUE)
Output:
Dani Laura Marta Sergio 263.00 271.90 422.45 199.25
Snippet 3. November’s amounts arrive copied from a spreadsheet set to Spanish.
nov <- c("12,50", "8,30", "47,90")
summ(nov)
Output:
Error in summ(nov) : is.numeric(x) is not TRUE
Here the bug is in the data, and the function is what catches it: the amounts are text with a decimal comma, and stopifnot(is.numeric(x)) stops dead with a message that says exactly which condition failed. Without that line, the error would have come from inside quantile, much less clearly.
Swap the comma for a point and convert to a number: as.numeric(sub(",", ".", nov)). If they come from a .csv, better to read it with read.csv2 or dec = "," (you saw it in R from scratch: data frames and functions).
nov <- as.numeric(sub(",", ".", nov))
summ(nov)
Output:
n mean Q1 median Q3 sd CV
3.00 22.90 10.40 12.50 30.20 21.75 94.99
outliers
0.00
Test: read the code
Ten questions on reading code: what each snippet prints or what is wrong with it. They do not count for anything and you can repeat them; try to answer without running anything and, if in doubt, check afterwards in the playground.
What does this code print?
f <- function(x, k = 2) x * k f(5) f(5, 3)
[1] 10and then[1] 15[1] 10and then[1] 10- An error, because
return()is missing [1] 7and then[1] 8
Solution
Answer: [1] 10 and then [1] 15
An argument with a default (k = 2) can be left out; if you pass it, yours wins. And the function returns the last expression it evaluates, here x * k.
What does the last line print?
g <- function(x) {
m <- mean(x)
}
g(c(2, 4, 6))- Nothing
[1] 4m- An error:
object 'm' not found
Solution
Answer: Nothing
A function returns the value of its last expression, and m <- mean(x) returns 4 but invisibly. With v <- g(c(2, 4, 6)), v would be 4. For it to show when called, the last line has to be m.
What number does this code print? Write just the number.
x <- c(4, NA, 8, 6) sum(is.na(x)) + length(x)
Solution
Answer: 5
is.na(x) gives FALSE TRUE FALSE FALSE and its sum counts the TRUEs: 1. length(x) counts every element, the NA too: 4. Total, 1 + 4 = 5.
What does this code print?
spend <- c(10, 20, 30, 40)
who <- c("Ana", "Luis", "Ana", "Luis")
tapply(spend, who, sum)Ana Luisand below40 60[1] 100[1] 40 60without names- A data frame with columns
whoandspend
Solution
Answer: Ana Luis and below 40 60
tapply(x, group, FUN) splits x by group (groups in alphabetical order) and applies FUN to each piece. It returns a named vector: Ana 40, Luis 60.
What is wrong with this code?
mean2 <- function(x) {
stopifnot(is.numeric(x))
round(mean(x), 2)
}
mean2(c("3,5", "4,1"))- It stops with
is.numeric(x) is not TRUE, because the data are text - It returns
3.8 - It returns
NAwith a warning - It fails because
return()is missing
Solution
Answer: It stops with is.numeric(x) is not TRUE, because the data are text
c("3,5", "4,1") is a character vector. stopifnot(is.numeric(x)) stops the function with an error that names the condition that failed. Fix: as.numeric(sub(",", ".", x)) before calling it.
What does this code print?
s <- c("B", "A", "B", "C", "B")
table(s)A B Cand below1 3 1(with the nameson top)B A Cand below3 1 1[1] 5[1] 3
Solution
Answer: A B C and below 1 3 1 (with the name s on top)
table counts how many times each value appears. With text, the groups come out in alphabetical order unless you convert to a factor with other levels.
With df having 4 rows, one of them with y equal to NA, how many rows does the result have?
df <- data.frame(g = c("a", "a", "b", "b"), y = c(1, NA, 3, 5))
nrow(aggregate(y ~ g, data = df, FUN = mean))[1] 2[1] 4[1] 3- An error because of the NA
Solution
Answer: [1] 2
The result has one row per group: a (mean 1, because the NA was dropped) and b (mean 4). So nrow gives 2.
What is wrong with this code?
x <- c(5, NA, 7, 9)
g <- c("a", "a", "b", "b")
clean <- na.omit(x)
tapply(clean, g, mean)- Error:
arguments must have same length - It gives
a 5andb 8 - It gives
a NAandb 8 - Nothing:
na.omitcannot be used with vectors
Solution
Answer: Error: arguments must have same length
Removing NAs from a loose vector misaligns it with the others. Remove rows from the whole table or use na.rm = TRUE inside the function.
About this function, mark true or false.
span <- function(x, na.rm = FALSE) {
if (na.rm) x <- x[!is.na(x)]
max(x) - min(x)
}span(c(3, 9, 4))returns 6.span(c(3, NA, 9))returns 6.span(c(3, NA, 9), na.rm = TRUE)returns 6.- You need to write
return(max(x) - min(x))for it to return the result.
Solution
- T —
span(c(3, 9, 4))returns 6. - F —
span(c(3, NA, 9))returns 6. - T —
span(c(3, NA, 9), na.rm = TRUE)returns 6. - F — You need to write
return(max(x) - min(x))for it to return the result.
Without na.rm = TRUE, the NA reaches max and min and the result is NA. With na.rm = TRUE, the if removes the NA first. And return() is not needed: the last expression is what gets returned.
What does this code print?
v <- c(2, 4, 6, 8) r <- c(mean = mean(v), n = length(v)) r["n"]
nand below4[1] 4meanand below5NA
Solution
Answer: n and below 4
c(mean = …, n = …) creates a named vector. r["n"] takes the element called n (4) and R prints it with its name on top. That is what makes it handy for summ() to return a named vector.
Try it in the R playground
Paste this script into the R playground and run it all. It is a short version of the whole article: data, function and plot.
# Five receipts and the summ() function in miniature
spend <- c(9.35, 51.60, NA, 12.10, 47.25)
shop <- c("Corner", "Market", "Corner", "Corner", "Market")
summ <- function(x, digits = 2) {
stopifnot(is.numeric(x))
x <- x[!is.na(x)]
round(c(n = length(x), mean = mean(x), median = median(x), CV = sd(x) / mean(x) * 100), digits)
}
summ(spend)
tapply(spend, shop, summ)
boxplot(spend ~ shop, main = "Spend by shop", ylab = "Euros")
What to look at:
- Environment shows
spend,shopandsumm: the function is just another object, like a vector. tapply(spend, shop, summ)returns a list with one vector per shop (because each result has several numbers); compare it with whatsapply(split(spend, shop), summ)gives.- In the plot, change
ylaband run the last line again: the plot is redrawn with the new label. - Type
summwithout brackets: R shows you the function’s code.
Cheat sheet: writing functions and descriptive statistics in R
The essentials in 30 seconds: a function is name <- function(arguments) { body } and returns its last expression; check the input with stopifnot, decide what to do with NAs and round at the end. To group, tapply (vector), aggregate (data frame) or sapply(split(…), f) (matrix).
| I want to… | Code | Result |
|---|---|---|
| Count by group | table(df$group) | frequency table (also counts rows with NA) |
| Sum by group | tapply(df$x, df$g, sum, na.rm = TRUE) | named vector |
| Mean by group as a table | aggregate(x ~ g, data = df, FUN = mean) | data frame (drops rows with NA) |
| My function by group | sapply(split(df$x, df$g), f) | matrix, one column per group |
| Stop if the input is bad | stopifnot(is.numeric(x), length(x) > 0) | error naming the condition that failed |
| Warn without stopping | message("Note: …") | message in the console, outside the result |
| Default value | function(x, digits = 2) | f(x) uses 2; f(x, 0) uses 0 |
| Outliers of a box plot | boxplot(…, plot = FALSE)$out | amounts of the outliers |
| Order of boxes or bars | factor(g, levels = c("B", "A")) | the order you choose |
| Readable plot | main = "…", xlab = "…", ylab = "…" | title and axes with units |
Templates from the exercises: summ(x) → n, mean, Q1, median, Q3, sd, CV and outliers; sapply(split(valid$spend, valid$shop), summ) → 8 × 3 matrix; settle(spend, who) → everyone’s balance, adding up to 0.
| Symptom | Likely cause |
|---|---|
| The function prints nothing | Its last line is an assignment (r <- …) |
NA instead of a number | There are NAs and they were not removed (na.rm = TRUE or filter) |
| “arguments must have same length” | You cleaned one vector and not the other columns |
| “is.numeric(x) is not TRUE” | The vector is text (decimal commas, a badly read .csv) |
The n from table and from aggregate differ | aggregate with a formula drops the rows with NA |
Before you hand it in, ask yourself:
- Do my functions check the input and report the NAs they remove?
- Have I rounded to 2 decimal places at the end, not halfway through the calculations?
- Does every plot have a title and axes with units?
- If the data change tomorrow, does the script still work without changing numbers by hand?
For your script
The block’s code, commented and without problem statements, ready to paste into your .R file for the ME1 exam. The functions are generic: they work for any vector or table, not just the receipts.
# ===================== Block R1: writing functions and descriptive statistics =====================
# summ(x, digits): n, mean, quartiles, sd, CV (%) and number of outliers (1.5·IQR rule)
summ <- function(x, digits = 2) {
stopifnot(is.numeric(x), length(x) > 0) # numeric, non-empty input
missing <- sum(is.na(x))
if (missing > 0) { # remove NAs, saying so
message("Note: removing ", missing, " NA value(s)")
x <- x[!is.na(x)]
}
q <- quantile(x, c(0.25, 0.5, 0.75), names = FALSE)
iqr <- q[3] - q[1]
outl <- sum(x < q[1] - 1.5 * iqr | x > q[3] + 1.5 * iqr)
round(c(n = length(x), mean = mean(x), Q1 = q[1], median = q[2], Q3 = q[3],
sd = sd(x), CV = sd(x) / mean(x) * 100, outliers = outl), digits)
}
# summ_groups(x, g): one column of summ() per group
summ_groups <- function(x, g, digits = 2) {
stopifnot(length(x) == length(g))
sapply(split(x, g), summ, digits = digits)
}
# outlier_rows(df, var, group): rows of df that the box plot flags as outliers within their group
outlier_rows <- function(df, var, group) {
b <- boxplot(df[[var]] ~ df[[group]], plot = FALSE)
if (length(b$out) == 0) return(df[0, ]) # no outliers: empty table
df[df[[var]] %in% b$out, ]
}
# settle(spend, who): each person's balance so that everyone pays the same (adds up to 0)
settle <- function(spend, who) {
stopifnot(is.numeric(spend), length(spend) == length(who))
paid <- tapply(spend, who, sum, na.rm = TRUE)
balance <- round(paid - mean(paid), 2)
stopifnot(abs(sum(balance)) < 0.05)
balance
}
# Typical use (swap df, "x" and "g" for your names):
# df <- df[!is.na(df$x), ] # drop incomplete rows
# summ(df$x)
# summ_groups(df$x, df$g)
# boxplot(x ~ g, data = df, main = "…", xlab = "…", ylab = "… (units)")
# outlier_rows(df, "x", "g")
# hist(df$x, breaks = seq(…), main = "…", xlab = "…", ylab = "Frequency")
# Quick check of the script with the receipts
summ_groups(valid$spend, valid$shop)["CV", ]
outlier_rows(valid, "spend", "shop")[, c("day", "who", "spend")]
Output:
Corner Market Online 23.14 24.92 4.65 day who spend 27 21 Dani 96.4
summ_groups passes digits = digits to sapply, which hands it to summ: the arguments you write after the function in sapply, tapply or aggregate reach that function. It is the same mechanism as na.rm = TRUE in tapply.
What next?
If something about the functions has not clicked, go back to the block’s theory, R intensive 1: descriptive statistics, where each piece is explained with its example. And if it is the statistics that limps, the ME1 descriptive statistics exercises work on it with the exam’s marking.
The next block is R intensive 2: probability and simulation: sample, set.seed and replicate to check with thousands of repetitions what the theory says.
Did this article help you? Here is how you can support SergioLearns →
Next blockR intensive 2: probability and simulation — Simulating with sample, set.seed and replicate, and checking the theory with thousands of repetitionsBlock theory: Your own functions, tapply, aggregate and plotsR intensive 1: descriptive statisticsCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script


