R intensive 1: descriptive statistics — your own functions, tapply and charts with my phone’s data usage (and the cv I copied from the line above)

Knowing how to compute a mean in R is not the same as knowing how to program the summary yourself. I realised it one Sunday, going over the descriptive statistics lab with a classmate: I swore my weekend data usage was “really irregular”, with a coefficient of variation of 0.39. He worked it out by hand and got 0.14. The mistake was not about statistics: I had copied the weekday cv line and only changed half of it. R did not complain, because the line was perfectly valid. That day I understood why people who know R write functions instead of copying and pasting.

This is the first block of the R programming intensive. Here descriptive statistics is taken as known (you have all of it in ME1 topic 1); what we are going to learn is how to program it: write your own functions, check what comes in, summarise by group without repeating code and draw charts that make sense without you standing next to them to explain.

In a nutshell: you write your own R function with function(arguments) { body }; it returns the last expression (or whatever you pass to return()) and it can check its input with stopifnot(). With it and with tapply, aggregate and base graphics, a complete descriptive summary by group fits in a few lines that never get it wrong when copied.

Before you start. To follow this article you only need three things from R: creating a vector with c(), taking pieces with brackets (mb[1], mb[type == "weekday"]) and the functions from topic 1 (mean, sd, quantile). The statistics are not new: you already know how to compute and interpret the mean, the quartiles, the coefficient of variation and the outliers. What is new is how the code is organised. The article has three pieces, in this order: writing your own functions (with their arguments and their checks); splitting the data into groups and summarising each one (table, tapply, aggregate); and drawing charts that explain themselves. Then we put them together in a program that is written four times, each one better than the last. If you get lost at any point, go back to the month’s MB: the whole article works with those same 30 numbers.

What you are going to program (and for which topic)

The example that comes with us is real in its shape, although the numbers are made up: the MB of mobile data I used each day for a month. Thirty days, starting on a Monday. On weekdays I use little (almost everything is wifi at uni and at home); at the weekend, a lot more; and on the last day there is a 2240 that is not a typo: I updated my phone without noticing it was not on wifi.

# The MB of mobile data I used each day of a 30-day month (it starts on a Monday)
mb <- c(412, 380, 455, 398, 520, 870, 940, 401, 377, 430, 465, 510, 905, 1020,
        389, 415, 442, 398, 560, 1310, 880, 420, 395, 410, 478, 530, 950, 990,
        405, 2240)
day <- rep(c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"), length.out = 30)
type <- ifelse(day %in% c("Sat", "Sun"), "weekend", "weekday")
week <- ceiling(seq_along(mb) / 7)   # days 1-7 = week 1, 8-14 = week 2…
length(mb)
table(type)

Output:

[1] 30
type
weekday weekend 
     22       8 

Three helper vectors built without typing 30 labels by hand: rep(…, length.out = 30) repeats the week until it fills 30 days (day 29 is a Monday again and day 30, a Tuesday); ifelse marks every day as “weekend” or “weekday” in one go, with no loop; and ceiling(seq_along(mb) / 7) numbers the weeks (day 8 gives 8/7 = 1.14, which rounded up is 2). There are 22 weekdays and 8 weekend days: 4 Saturdays and 4 Sundays, because the month does not reach a fifth full week.

The three labels, checked day by day

Four functions in three lines is a lot in one go. So, before moving on, let us look at what comes out on a few specific days. The easiest way is to put the vectors together in a data frame and ask for just a few rows:

# The three labels of a few days, to check them by hand
data <- data.frame(mb, day, type, week)
data[c(1, 6, 7, 8, 29, 30), ]

Output:

     mb day    type week
1   412 Mon weekday    1
6   870 Sat weekend    1
7   940 Sun weekend    1
8   401 Mon weekday    2
29  405 Mon weekday    5
30 2240 Tue weekday    5

Every row has its reason, and it is worth saying it out loud at least once:

DaydaytypeweekWhy
1Monweekday1rep starts at the beginning of the 7-day vector; “Mon” is not in the weekend list; 1/7 = 0.14, which rounded up is 1
6Satweekend1sixth position of the 7-day vector; “Sat” is in the list, so ifelse picks “weekend”; 6/7 = 0.86, rounded up 1
7Sunweekend17/7 = 1 exactly, and ceiling of a whole number is the same number: Sunday closes week 1
8Monweekday2rep starts again; 8/7 = 1.14, rounded up 2
29Monweekday529 = 4 · 7 + 1: first position of the fifth round; 29/7 = 4.14, rounded up 5
30Tueweekday5rep stops here because length.out = 30; 30/7 = 4.29, rounded up 5

Notice the role of %in%. day %in% c("Sat", "Sun") asks, day by day, “is this value in the list?”, and returns 30 TRUE or FALSE values. ifelse reads them one by one: where there is a TRUE it writes “weekend” and where there is a FALSE, “weekday”. It is an if for whole vectors; the normal if only looks at one value.

Why ceiling and not round? Because round goes to the nearest whole number: round(3/7) is 0, so days 1, 2 and 3 would fall into a “week 0” and days 4 to 10 would end up together in week 1. ceiling always rounds up, which is why each block of 7 days lands whole in its own week.

Check you’ve got it: what are day, type and week on day 14? And on day 15?

Day 14 is 2 · 7, the seventh position of the second round: “Sun”, and therefore “weekend”. 14/7 = 2 exactly, so ceiling leaves it in week 2: Sunday closes its week, just like day 7.

On day 15, rep starts again: “Mon”, “weekday”. 15/7 = 2.14, which rounded up is 3: the first day of week 3. The data agree: mb[14] is 1020 (Sunday, high usage) and mb[15] is 389 (Monday, back on wifi).

What are we going to build with this?

  • A function summary_stats() that, given any vector, returns the size, the mean, the quartiles, the coefficient of variation and the outliers, with its checks.
  • The same summary by group (weekday against weekend) without writing it twice.
  • The base graphics of topic 1 (histogram, boxplot, bars) with titles and axes that say something.

You already know how to interpret everything it computes if you have done topic 1 and its R practice. If c(), data frames or function sound like gibberish, read R from scratch: data frames and functions first; here we go one step further.

The R pieces you need

Your own function: function, arguments and what it returns

A function is a recipe with a name: you give it ingredients (the arguments), it does something with them (the body) and it gives you back a result. In R you create it like any other object, with <-:

# A minimal function: it takes a vector and returns its range
spread <- function(x) {
  max(x) - min(x)          # the last expression is what it returns
}
spread(mb)
spread(c(10, 4, 7))

Output:

[1] 1863
[1] 6

The range of the month is 2240 − 377 = 1863 MB, and that of c(10, 4, 7) is 10 − 4 = 6. Notice three things that confuse you at first:

  • You do not need return(). R returns the value of the last expression the body evaluates. max(x) - min(x) is the last (and only) one, so that is what comes out.
  • x only exists inside. When you call spread(mb), R creates a local x that holds the same as mb. When it finishes, that x disappears; your mb outside is not touched.
  • Defining is not running. The line spread <- function(x) {…} computes nothing: it stores the recipe. It runs when you call it with parentheses.
Anatomy of your own R functionThe code of the cv function with each part marked in a colour: the name, the arguments with one default, the stopifnot check, the early exit with return and the last expression, which is what it returns. Below, the call cv(mb) gives 0.62.The parts of your own functioncv <- function(x, digits = 2) { stopifnot(is.numeric(x)) if (mean(x) == 0) return(NA) round(sd(x) / mean(x), digits)}name: stored with <-arguments (one with a default)check the inputleave early with return()last line: what it returnsCall:cv(mb)→ 0.62inside, x holds mb; outside, x does not exist
Defining the function stores the recipe; calling it with parentheses runs it.

Look at the drawing: every part of a function has its place. The arguments go inside the parentheses of function, the body inside the braces, and what comes out is the last line (or whatever you put in return(), which we will see in a moment).

What R does when you type spread(mb)

The three ideas in the list are easier to see if we follow one call from the inside, step by step:

StepWhat R doesWhy
1It looks for an object called spread and sees that it is a functionyou stored it earlier with <-; if you had not run that line, R would give an error because it cannot find it
2It opens a new space, just for this call, and puts x = the 30 values of mb inside itx is a temporary name for whatever you pass, whatever it is
3It evaluates max(x) - min(x): 2240 − 377 = 1863it is the last (and only) expression in the body
4It returns 1863 and deletes that space, with its x insidethat is why x does not exist outside and mb stays the same

The second call, spread(c(10, 4, 7)), repeats the four steps with a different x: the same code, different data. That is the whole point of a function.

Check you’ve got it: if a function changes its x inside, does mb change too?

No. Try it with this function, which doubles x and returns its first value:

double_it <- function(x) {
  x <- x * 2          # changes the x inside, not the one outside
  x[1]
}
double_it(mb)
mb[1]

Output:

[1] 824
[1] 412

Inside, x became twice mb, and its first value is 412 · 2 = 824. But mb[1] is still 412: the function worked with its own copy, and that copy was deleted when it finished (step 4). If you want to keep the change, you have to do it outside, with an assignment: mb2 <- double_it(mb) would store the 824, and mb2 <- mb * 2, the whole doubled vector.

Arguments with a default value and calls by name

Many R functions have arguments you hardly ever touch: mean(x, na.rm = FALSE), round(x, digits = 0). Those are default values, and you can set them too:

# Arguments with a default value: if you do not give them, these are used
to_gb <- function(x, digits = 2, binary = TRUE) {
  divisor <- if (binary) 1024 else 1000
  round(x / divisor, digits)
}
to_gb(2240)                     # uses digits = 2 and binary = TRUE
to_gb(2240, 1)                  # by position: digits = 1
to_gb(2240, binary = FALSE)     # by name: skips digits

Output:

[1] 2.19
[1] 2.2
[1] 2.24

Let us check all three by hand: 2240 / 1024 = 2.1875, which with 2 decimals is 2.19; with 1 decimal, 2.2 (R does not print the final 0 of 2.20); and 2240 / 1000 = 2.24. The third call is the interesting one: since binary is the third argument, to change it without touching digits you name it. By position R fills the arguments in order; by name you can skip whichever you like, in any order.

How R hands out the arguments

The rule has two steps, and it is worth putting it into words: first R puts the arguments that have a name in their place; then it hands out the ones without a name, in order, among the slots that are still free. Whatever nobody fills keeps its default value. With the calls above (and one more):

CallxdigitsbinaryWhy
to_gb(2240)22402TRUEa single unnamed value, to the first slot; the other two, by default
to_gb(2240, 1)22401TRUEtwo unnamed values: the first to x and the second to digits
to_gb(2240, binary = FALSE)22402FALSEbinary goes by name to its place; 2240 fills the first free slot, x
to_gb(digits = 1, 2240)22401TRUEthe name first; 2240 goes to the first free slot, which is x. It works, but it reads worse

And what if you want to change binary without writing its name? Here is the trap:

to_gb(2240, FALSE)   # by position: FALSE lands in digits, not in binary
to_gb(2240, binary = FALSE)

Output:

[1] 2
[1] 2.24

The first call gives 2, not 2.24. The FALSE took the second slot, digits, and in a calculation FALSE is worth 0. So binary is still TRUE: it divides by 1024 and rounds 2.1875 with no decimals, 2. Not an error, not a warning.

Passing by position an argument that is not the next one in the list. If you have to skip one, name the one you want to change. And in the exam, when in doubt, name them all: to_gb(2240, digits = 2, binary = FALSE) cannot be misread.

Put the required arguments (the data) first and the ones with default values after them. That way the shortest call, to_gb(2240), is also the most common one.

Something else you have just seen: if (binary) 1024 else 1000 is an if that returns a value. In R, if is an expression, not just a statement, so you can store it in a variable. It is perfect for choosing between two values without four lines of braces.

Checking the input with stopifnot (and leaving early with return)

A function that takes rubbish and returns a number that looks right is worse than a function that stops. That is what stopifnot() is for: you give it conditions and, if any is false, it stops with an error saying which one.

# return() to leave early; stopifnot() not to swallow rubbish
cv <- function(x) {
  stopifnot(is.numeric(x), length(x) >= 2)
  if (mean(x) == 0) return(NA)   # with no mean there is no ratio worth having
  sd(x) / mean(x)
}
round(cv(mb), 2)
cv(c(0, 0, 0))

Output:

[1] 0.62
[1] NA

The coefficient of variation of the month is 0.62: the standard deviation is 62 % of the mean, a large spread (topic 1 tells you how to read it; here we care about how it is programmed). The second call never gets to divide: since the mean is 0, return(NA) leaves the function at that line and the last one is never evaluated. return() is for leaving early, not for returning the normal result.

And if I pass it text?

cv(c("412", "380"))

Output:

Error in cv(c("412", "380")) : is.numeric(x) is not TRUE

stopifnot tells you exactly which condition failed: is.numeric(x) is not TRUE. That happens a lot when you read a CSV and a column arrives as text because of a decimal comma: without the check, mean() would have returned NA with a warning lost among the output.

Check you’ve got it: what do cv(412) and cv(c(-5, 5)) return?

cv(412) stops at the first line of the body. 412 is numeric, so the first condition passes, but it is a single value, and the second one (length(x) >= 2) fails. R says it like this:

Error in cv(412) : length(x) >= 2 is not TRUE

It makes sense: with one value there is no standard deviation (sd(412) gives NA), so there is no cv either.

cv(c(-5, 5)) passes both checks: it is numeric and has 2 values. But its mean is (−5 + 5) / 2 = 0, so return(NA) leaves before dividing and returns NA. The order of the lines matters: the checks go first, because it makes no sense to ask for the mean of something that is not numbers.

What should you check? Whatever would make the result meaningless: that it is numeric, that there is enough data (a standard deviation needs at least 2 values), that a probability is between 0 and 1. You do not need to check everything; whatever would make you wrong in silence is enough.

Counting and grouping: table, tapply and aggregate

Three functions for the same idea: split the data into groups and do something in each one.

table counts how many times each value appears, or each combination of values if you give it two vectors:

# table: how many times each value (or each pair) appears
table(type)
table(type, high_use = mb > 500)

Output:

type
weekday weekend 
     22       8 
         high_use
type      FALSE TRUE
  weekday    17    5
  weekend     0    8

The two-way table is read by rows: of the 22 weekdays, 17 did not go over 500 MB and 5 did; of the 8 weekend days, none stayed below. Notice the trick of high_use = mb > 500: the name you give the argument becomes the title of the columns.

tapply(x, group, f) applies the function f to the pieces of x that share a value in group:

# tapply: applies a function to each group of a vector
tapply(mb, type, mean)
round(tapply(mb, week, median), 1)

Output:

 weekday  weekend 
519.5455 983.1250 
     1      2      3      4      5 
 455.0  465.0  442.0  478.0 1322.5 

The weekday mean is 519.55 MB and the weekend one, 983.12. By week, the median stays between 442 and 478 until the fifth “week” arrives, which only has two days (405 and 2240), so its median is the mean of the two: (405 + 2240) / 2 = 1322.5. That number says nothing about how week 5 went; it says that a group with two values cannot carry a summary.

What tapply does insideThe 30-day vector is split into two groups, weekday with 22 values and weekend with 8; mean is applied to each, giving 519.5455 and 983.1250; and the results are combined into a named vector.Split · apply · combinemb30 days, each with its group (violet = weekday, coral = weekend)split(mb, type)$weekday22 values: 412 380 455 398 …$weekend8 values: 870 940 905 1020 …mean()mean()519.5455983.1250weekday weekend519.5455 983.1250a named vector
tapply(mb, type, mean) = split, apply mean to each piece and combine.

The drawing shows what tapply does inside, and it is the most useful idea of the block: split (split), apply the function to each piece and combine the results into a named vector. We will use it again in the complete program.

Split, apply, combine, done by hand

Before you trust tapply, it is worth doing its three steps yourself, one per line. That way, when something looks odd, you will know which step to look at.

# Split, apply, combine, by hand (what tapply does inside)
pieces <- split(mb, type)   # split: a list with one vector per group
lengths(pieces)
means <- sapply(pieces, mean)   # apply mean to each piece and combine
round(means, 2)
round(tapply(mb, type, mean), 2)

Output:

weekday weekend 
     22       8 
weekday weekend 
 519.55  983.12 
weekday weekend 
 519.55  983.12 
  • Split. split(mb, type) looks at type position by position and puts each value of mb into the drawer of its label. lengths (with an s) counts how many there are in each drawer: 22 and 8, the same as table(type) gave.
  • Apply and combine. sapply goes through the list, applies mean to each drawer and combines the two results into a vector named after the drawers.
  • Check. The last two outputs are the same: 519.55 and 983.12. tapply does nothing more than this, in a single call.

If a figure per group looks odd, do the split on its own and look at the drawers. The mistake is almost always in the group vector, not in the function: a misspelt label (“Weekend” with a capital letter) creates a separate drawer. And the drawers come out in alphabetical order (weekday before weekend), not in the order they appear in the data.

aggregate does the same but works with a data frame and a formula (variable ~ group), which is how the data comes in the exam:

# aggregate: the same, but with a data frame and a formula
data <- data.frame(mb, day, type, week)
aggregate(mb ~ type, data = data, FUN = median)

Output:

     type    mb
1 weekday 417.5
2 weekend 945.0

The output is a data frame (with its row numbers on the left), not a vector: you can store it and keep working with it. The weekday median, 417.5, is well below its mean, 519.55: you can already feel the pull of the 2240.

I want…I useIt gives me
To count how many of each thingtable(g) or table(g1, g2)a frequency table
One figure per group of a vectortapply(x, g, f)a named vector
One figure per group in a data frameaggregate(x ~ g, data, FUN)a data frame
Several figures per groupsapply(split(x, g), f)a matrix (coming shortly)

Base graphics with titles and axes that say something

Base R charts are made with a single call, and almost all of them accept the same presentation arguments: main (title), xlab and ylab (axes), col (fill) and border (border).

hist(mb, breaks = seq(0, 2400, by = 300),
     main = "Mobile data in a month", xlab = "MB per day",
     ylab = "Number of days", col = "#A99EF5", border = "white")

There is no text output: the result is the chart, which in RStudio appears in the Plots panel. This is it:

Histogram of the daily MB of the monthHistogram with 300 MB classes from 0 to 2400. Frequencies: 0, 21, 2, 5, 1, 0, 0 and 1. Most days are between 300 and 600 MB and a single day sits alone between 2100 and 2400.03006009001200150018002100240005101520Number of daysMB per dayMobile data in a month212511the 2240
The chart hist() draws: 21 normal weekdays, the weekend between 600 and 1500 and the 2240 alone at the end.

In the drawing, the bar from 300 to 600 MB has 21 days: that is the normal weekday. The bars from 600 to 900 (2 days) and from 900 to 1200 (5) are all weekend days, the 1310 falls alone between 1200 and 1500, and the 2240 is left isolated at the end. The breaks every 300 are no accident: with breaks = seq(0, 2400, by = 300) I choose them myself instead of letting R decide; that way the axis shows round numbers and the classes are equal.

Leaving the default title and axes. hist(mb) uses “Histogram of mb” as its title and “mb” as its axis. In the exam, and in any report, a chart without units cannot be understood: “MB per day” and “Number of days” take ten seconds.

The complete program: from copy and paste to summary_stats()

Now we put the pieces together. The goal: the complete descriptive summary of the month’s data, overall and by type of day. We are going to do it four times, each better than the last, because that is how programming really works: first something that works, then something that does not get it wrong.

Version 1: copy and paste

Everybody’s first idea (mine too, the one with the wrong cv): separate the groups and compute each figure by hand.

# Version 1: copy and paste for each group (with a hidden mistake)
mb_weekday <- mb[type == "weekday"]
mb_weekend <- mb[type == "weekend"]
mean_weekday <- mean(mb_weekday)
cv_weekday <- sd(mb_weekday) / mean(mb_weekday)
mean_weekend <- mean(mb_weekend)
cv_weekend <- sd(mb_weekday) / mean(mb_weekend)     # copied from above!
round(c(mean_weekday, cv_weekday, mean_weekend, cv_weekend), 2)

Output:

[1] 519.55   0.75 983.12   0.39

It works, it gives numbers, and one is wrong: the weekend cv comes out as 0.39 because it divides the standard deviation of the weekdays by the weekend mean. Not an error, not a warning. And that is with only two groups and two figures: with four groups and six figures there would be 24 almost identical lines, 24 places to get it wrong.

Copied and pasted code does not fail, it gets things wrong. If you catch yourself copying a line to change a name, it is time to write a function.

Version 2: a summary_stats() function

We write the recipe once and use it with any vector:

# Version 2: a function that summarises any vector
summary_stats <- function(x) {
  q <- quantile(x, c(0.25, 0.5, 0.75))
  c(n = length(x), mean = mean(x), Q1 = q[[1]], median = q[[2]],
    Q3 = q[[3]], cv = sd(x) / mean(x))
}
round(summary_stats(mb), 2)
round(summary_stats(mb[type == "weekend"]), 2)

Output:

     n   mean     Q1 median     Q3     cv 
 30.00 643.17 406.25 460.00 877.50   0.62 
     n   mean     Q1 median     Q3     cv 
  8.00 983.12 898.75 945.00 997.50   0.14 

Now the weekend cv is 0.14, the right one: the standard deviation and the mean come from the same x, because inside the function there is only one x. There is no way to mix groups.

Two details in the code worth zooming into:

  • q[[1]] and not q[1]. quantile returns a named vector (“25%”, “50%”, “75%”). With q[1] the name travels with the number and the result would be called Q1.25%; with double brackets you get the number on its own and the name that counts is the one you give it (Q1 =).
  • c(n = …, mean = …) builds a named vector: each figure carries its label, which is why the output reads by itself.

Where 406.25 comes from

Q1 = 406.25 is none of the 30 values. By default, quantile does not pick a value from the list: it places the quartile at a position that can fall between two sorted values and shares out the distance between them. R’s rule is: position = 1 + (n − 1) · p. For Q1, step by step:

StepCalculationWhy
1sort: 377, 380, 389, 395, 398, 398, 401, 405, 410, 412…quartiles are always looked for on the sorted data
2position = 1 + (30 − 1) · 0.25 = 8.25n = 30 and p = 0.25 for the first quartile
3the 8th value is 405 and the 9th, 4108.25 falls between those two positions
4405 + 0.25 · (410 − 405) = 406.25the 0.25 left over from 8.25 says what part of the way from 405 to 410 you move

Q3 works the same way: 1 + 29 · 0.75 = 22.75, between the 22nd value (870) and the 23rd (880), and 870 + 0.75 · 10 = 877.5. The median falls at position 1 + 29 · 0.5 = 15.5, exactly halfway between the 15th (455) and the 16th (465): 460.

There are several ways to compute quartiles (quantile accepts nine, through the type argument), and with few data they give slightly different numbers. R uses type = 7 by default, the one in this table. If by hand, or with the hinges of boxplot (you will see them in version 3), you get a slightly different Q1, R has not made a mistake: it is a different rule.

Version 3: checks, NA and outliers

Version 2 has three holes: it accepts text, it breaks with an NA (the day my phone ran out of battery and I did not write anything down) and it says nothing about outliers. Let us plug them:

# Version 3: checks the input, removes NAs and looks for outliers
summary_stats <- function(x, na.rm = TRUE, k = 1.5, digits = 2) {
  stopifnot(is.numeric(x))
  if (na.rm) x <- x[!is.na(x)]
  stopifnot(length(x) >= 2)
  q <- quantile(x, c(0.25, 0.5, 0.75))
  iqr <- q[[3]] - q[[1]]
  fences <- c(q[[1]] - k * iqr, q[[3]] + k * iqr)
  outliers <- x[x < fences[1] | x > fences[2]]
  tab <- c(n = length(x), mean = mean(x), Q1 = q[[1]], median = q[[2]],
           Q3 = q[[3]], cv = sd(x) / mean(x), outliers = length(outliers))
  list(table = round(tab, digits), fences = fences, outliers = outliers)
}
r <- summary_stats(c(mb, NA))      # a day with no data: the phone's battery died
r$table
r$fences
r$outliers

Output:

       n     mean       Q1   median       Q3       cv outliers 
   30.00   643.17   406.25   460.00   877.50     0.62     1.00 
[1] -300.625 1584.375
[1] 2240

I passed it the 30 values plus an NA and the table says n = 30: the NA was removed before counting. Let us follow the calculation inside, step by step:

StepLineValue afterwards
1stopifnot(is.numeric(x))passes: c(mb, NA) is numeric (an NA does not change the type)
2x <- x[!is.na(x)]x has 30 values again
3stopifnot(length(x) >= 2)passes: 30 ≥ 2
4q <- quantile(…)Q1 = 406.25, median = 460, Q3 = 877.5
5iqr <- q[[3]] - q[[1]]877.5 − 406.25 = 471.25
6fences <- …406.25 − 1.5 · 471.25 = −300.625 and 877.5 + 1.5 · 471.25 = 1584.375
7outliers <- x[…]only 2240 is above 1584.375
8list(…)returns all three things at once
The fences of resumen() and the only outlierDot plot of the 30 days. The fences are at −300.625 and 1584.375 (Q1 − 1.5·IQR and Q3 + 1.5·IQR). Every point is inside except 2240.-40004008001200160020002400MBlower fence −300.6upper fence 1584.4Q1 = 406.25 · Q3 = 877.5 · IQR = 471.25outlier
Only 2240 falls outside the fences; the lower one is negative, so there can be no low outliers.

In the drawing, each dot is a day; the dashed lines are the fences and only 2240 falls outside. The lower fence is negative, so there can be no outliers on that side: negative MB do not exist.

Why return a list and not a vector? Because the three things have different sizes: the table has 7 figures, the fences 2 and the outliers, however many there are (0, 1 or 5). A vector would mix them into a shapeless strip; a list keeps them in named drawers, and you take them out with $: r$table, r$fences, r$outliers.

And the new arguments have default values: k = 1.5 is the usual rule for outliers, but if one day you are asked for the extreme-outlier rule, summary_stats(mb, k = 3) and you are done.

The fences of summary_stats() come from quantile, and those of boxplot come from Tukey’s “hinges” (fivenum), which can differ slightly with little data. In the weekday group, for example, quantile gives Q1 = 398.75 and boxplot draws the box from 398. The outliers almost always match; if one day they do not, now you know why.

Version 4: by group, in one go

What version 1 did by hand is still missing: the summary of each type of day. With split we split and with sapply we apply and combine:

# Version 4: the same function for each group, in one go
by_type <- sapply(split(mb, type), function(g) summary_stats(g)$table)
by_type

Output:

         weekday weekend
n          22.00    8.00
mean      519.55  983.12
Q1        398.75  898.75
median    417.50  945.00
Q3        474.75  997.50
cv          0.75    0.14
outliers    1.00    1.00

One line and a matrix with everything: one column per group and one row per figure. Let us take it apart:

  1. split(mb, type) splits mb into a list with two vectors: $weekday (22 values) and $weekend (8).
  2. function(g) summary_stats(g)$table is an anonymous function: it has no name because it is only used here. It takes a group and returns only the table of its summary.
  3. sapply applies it to each element of the list and, since every answer has 7 figures, puts them together as columns. If they had different sizes, it would return a list.

And the matrix tells a story the mean alone did not: weekdays have a cv of 0.75 (very spread out) only because of 2240, their only outlier; the weekend, on the other hand, is regular (0.14) even though it uses twice as much, and its only outlier is 1310. Why did I not use tapply here? Because tapply is meant for functions that return one number per group; for several, sapply(split(…)) gives a clean matrix.

Check you’ve got it: what does sapply return if you change $table to $outliers? And to $fences?

Try it:

sapply(split(mb, type), function(g) summary_stats(g)$outliers)
sapply(split(mb, type), function(g) summary_stats(g)$fences)

Output:

weekday weekend 
   2240    1310 
     weekday  weekend
[1,]  284.75  750.625
[2,]  588.75 1145.625

With $outliers, each group returns a single number (each one has one outlier), so sapply combines them into a named vector: 2240 for weekday and 1310 for weekend. With $fences, each group returns two numbers, and sapply puts them in columns: a matrix with the lower fence in row 1 and the upper one in row 2. Check it with the weekdays: the IQR is 474.75 − 398.75 = 76, and 398.75 − 1.5 · 76 = 284.75 and 474.75 + 1.5 · 76 = 588.75.

The rule of sapply is always the same: if all the answers have the same size, it simplifies (a vector if they have length 1, a matrix if they are longer); if not, it returns a list. That is why, if you split by week (split(mb, week)), where one week has an outlier and the others none, $outliers comes out as a list.

The chart that goes with this table is the boxplot by group, with the same formula as aggregate:

boxplot(mb ~ type, data = data, main = "MB per day by type of day",
        xlab = "", ylab = "MB", col = c("#A99EF5", "#FFB4A3"))
Boxplot of the MB by type of dayTwo boxplots. Weekday: box from 398 to 478, median 417.5, whiskers from 377 to 560 and an outlier at 2240. Weekend: box from 892.5 to 1005, median 945, whiskers from 870 to 1020 and an outlier at 1310.0500100015002000MBMB per day by type of dayweekdaymedian 417.52240weekendmedian 9451310
The two boxes do not even touch: the type of day explains almost all the difference in usage.

In the drawing, the weekday box is low and narrow (from 398 to 478) with 2240 as a lone point far above; the weekend one is entirely higher (from 892.5 to 1005), with 1310 on its own. The two boxes do not even touch: the type of day explains almost all the difference in usage. It is the same conclusion as the matrix, but you see it in a second.

Common mistakes (with R’s real message)

All these messages are exactly what R prints. Learn to read them: they almost always say exactly what is going on.

Calling the function without a required argument.

cv()

Output:

Error in cv() : argument "x" is missing, with no default

“argument “x” is missing, with no default”: the argument x has no default value and you have not given it. Either pass it or give it a default in the definition.

Misspelling the name of an argument.

to_gb(2240, decimals = 1)

Output:

Error in to_gb(2240, decimals = 1) : unused argument (decimals = 1)

“unused argument (decimals = 1)”: to_gb has no argument called decimals (it is called digits). R does not guess; look at the definition or, for R’s own functions, the help with ?name.

Forgetting the NAs.

mean(c(mb, NA))

Output:

[1] NA

No error message, and that is the dangerous part: a single NA turns the mean into NA. R functions do not remove NAs unless you ask (na.rm = TRUE). Our summary_stats() does it by default, which is why it has the na.rm argument.

Grouping with a vector of a different length.

tapply(mb, day[1:28], mean)

Output:

Error in tapply(mb, day[1:28], mean) : arguments must have same length

“arguments must have same length”: mb has 30 values and the group, 28. It happens when you filter the data but not the group vector (or the other way round). Filter both with the same condition, or better, work with a data frame and aggregate, which keeps them together.

A function that ends in an assignment.

summary_stats <- function(x) {
  avg <- mean(x)
}
summary_stats(mb)
r2 <- summary_stats(mb)
r2

Output:

[1] 643.1667

The first call, summary_stats(mb), prints nothing. It looks as if the function returns nothing, but it does: it returns the value of the assignment, which is invisible. If you store it in r2 and print it, there it is: 643.1667. To avoid the scare, end the body with the value you want to return (avg on its own on the last line), not with an assignment.

Changing a function (as I have just done with summary_stats) and forgetting that the old version no longer exists. In R, defining a function again with the same name replaces it. If your script has two summary_stats <- function…, the one that counts is the last one that ran.

Try it in the R playground

Copy this script into the R playground on the site (or into RStudio) and run all of it. It has the data inside, so you do not need anything else.

mb <- c(412, 380, 455, 398, 520, 870, 940, 401, 377, 430, 465, 510, 905, 1020,
        389, 415, 442, 398, 560, 1310, 880, 420, 395, 410, 478, 530, 950, 990,
        405, 2240)
type <- ifelse(rep(1:7, length.out = 30) >= 6, "weekend", "weekday")

summary_stats <- function(x, na.rm = TRUE, k = 1.5, digits = 2) {
  stopifnot(is.numeric(x))
  if (na.rm) x <- x[!is.na(x)]
  stopifnot(length(x) >= 2)
  q <- quantile(x, c(0.25, 0.5, 0.75))
  iqr <- q[[3]] - q[[1]]
  fences <- c(q[[1]] - k * iqr, q[[3]] + k * iqr)
  outliers <- x[x < fences[1] | x > fences[2]]
  tab <- c(n = length(x), mean = mean(x), Q1 = q[[1]], median = q[[2]],
           Q3 = q[[3]], cv = sd(x) / mean(x), outliers = length(outliers))
  list(table = round(tab, digits), fences = fences, outliers = outliers)
}

sapply(split(mb, type), function(g) summary_stats(g)$table)
boxplot(mb ~ type, main = "MB per day by type of day", ylab = "MB")

What to look at:

  1. In the Environment panel, summary_stats shows up as a function (function (x, na.rm = TRUE, …)), not as data. Click on it and you will see its code.
  2. Change k = 1.5 to k = 3 in the call: sapply(split(mb, type), function(g) summary_stats(g, k = 3)$table). Are 2240 and 1310 still outliers?
  3. Type summary_stats("hello") in the console and read the stopifnot message.
  4. In the Plots chart, compare the boxes with the matrix in the console: the medians are the thick lines.
  5. Add a third group: type[c(5, 12, 19, 26)] <- "friday" and run the last two lines again. The function does not change; one more column appears.

Summary

PieceWhat forExample from the article
function(x, a = value) { … }write the recipe onceto_gb(2240, binary = FALSE)
Last expression / return()what it returns / leave earlyreturn(NA) if the mean is 0
stopifnot(cond1, cond2)stop if the input is no goodis.numeric(x) is not TRUE
list(a = …, b = …)return several things of different sizesr$table, r$outliers
table, tapply, aggregatecount and summarise by groupmean by type: 519.55 and 983.12
sapply(split(x, g), f)several figures per group, in a matrixthe weekday/weekend matrix
hist, boxplot, barplot + main, xlab, ylabcharts that read by themselvesthe boxplot by type of day

Three ideas to take with you:

  1. If you copy a line to change a name, write a function. Copy and paste does not fail: it gets things wrong in silence.
  2. A function checks whatever would make it lie. stopifnot and na.rm cost one line and save you a wrong result that looks right.
  3. Split, apply, combine. split + sapply (or tapply, or aggregate) is the pattern behind every summary by group, in topic 1 and in all the ones to come.

What next?

The theory is done; now you have to write it yourself. In the R intensive 1 exercises there are functions to complete, a full problem in the format of the exam script, broken code to fix and the cheat sheet for the block.

When you have it, carry on with block 2: probability and simulation, where these same functions start rolling dice, opening sticker packets and repeating experiments thousands of times with replicate.

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

Next step: exercisesR 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)Next block: sample, set.seed, replicate and the d/p/q/r familyR intensive 2: probability and simulationCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script