From typing commands to writing tools
So far you have called R's functions. Real analysis soon needs your own: the same cleaning steps applied to twelve monthly files, the same summary computed for every region, a calculation used in three places that should be written once and tested once. A function is how you name a piece of work, give it inputs, and reuse it.
R is a functional language at heart, which shapes how its programmers work. Functions are ordinary values: you can store them in lists, pass them to other functions, and return them from functions. Instead of writing a loop that walks over a list and builds up a result, R programmers usually hand a function to lapply() or sapply() and let it do the walking. And since version 4.1, the native pipe |> lets you write a sequence of function calls in the order they happen, which has changed the look of modern R code.
This lesson covers writing functions, the control flow inside them, the "apply" family of functions that replace most loops, the pipe, closures, and what to do when things go wrong. Together they are the difference between a script that works once and code you can trust, reuse and hand to someone else.
Writing functions
Definition— Function
A function is created with function(arguments) body and usually assigned to a name. When called, it evaluates its body in a fresh environment where the arguments are bound to the values passed, and returns the value of the last expression evaluated (or of an explicit return(value)).
# A function is created with function() and stored in a variable.
# The value of the last expression is returned.
bmi <- function(weight_kg, height_m) {
weight_kg / height_m^2
}
bmi(70, 1.75)
bmi(height_m = 1.6, weight_kg = 55) # named arguments, any order
bmi(c(70, 55, 90), c(1.75, 1.6, 1.8)) # vectorised for free
# Defaults, and a default that refers to another argument (lazy evaluation).
describe <- function(x, digits = 2, label = deparse(substitute(x))) {
stopifnot(is.numeric(x)) # fail early with a clear message
m <- round(mean(x, na.rm = TRUE), digits)
s <- round(sd(x, na.rm = TRUE), digits)
paste0(label, ": mean ", m, ", sd ", s, " (n = ", sum(!is.na(x)), ")")
}
describe(faithful$waiting)
describe(airquality$Ozone, digits = 1, label = "ozone")
# To return several results, return a list.
range_info <- function(x) {
list(min = min(x), max = max(x), span = diff(range(x)))
}
info <- range_info(faithful$eruptions)
info$span
str(info)[1] 22.85714
[1] 21.48437
[1] 22.85714 21.48437 27.77778
[1] "faithful$waiting: mean 70.9, sd 13.59 (n = 272)"
[1] "ozone: mean 42.1, sd 33 (n = 116)"
[1] 3.5
List of 3
$ min : num 1.6
$ max : num 5.1
$ span: num 3.5Because bmi only uses vectorised arithmetic, it works on whole vectors without any extra effort: write functions in terms of vector operations and they inherit that power.
describe shows three habits of good R functions. Arguments with defaults (digits = 2) can be left out. The first line checks its input with stopifnot(), so that a wrong call fails immediately with a clear message instead of producing nonsense later. And the default for label uses deparse(substitute(x)), which turns the expression the caller wrote, faithful$waiting, into text. That trick works because R evaluates arguments lazily: an argument's expression is not computed until the function first uses it, so a default can depend on other arguments or on how the function was called.
A function returns one value, so to return several results, return a named list, as range_info does. This is exactly what R's own statistical functions do.
Choosing and repeating
if (condition) … else … needs a condition that is a single TRUE or FALSE. It is an expression with a value, so label <- if (x > 0) "positive" else "not positive" is natural R. For a decision made separately for every element of a vector, use the vectorised ifelse(test, yes, no). For choosing among several named alternatives, switch() is tidier than a chain of else if.
Loops exist too: for (x in values), while (condition) and repeat (with break), and next skips to the next iteration. They are the right tool when each step depends on the previous one, as in a simulation or a running balance, and for side effects such as writing files. When you loop to build a result, create it at full length first and fill it by position.
# if/else takes a single TRUE or FALSE, and is itself an expression.
grade <- function(score) {
if (is.na(score)) {
"absent"
} else if (score >= 70) {
"distinction"
} else if (score >= 50) {
"pass"
} else {
"not yet"
}
}
grade(82); grade(NA)
# ifelse() is the vectorised version: one result per element.
scores <- c(82, 45, NA, 67)
ifelse(scores >= 50, "pass", "not yet")
# switch() picks a branch by name.
to_metres <- function(x, unit) {
switch(unit,
km = x * 1000,
mi = x * 1609.344,
ft = x * 0.3048,
stop("unknown unit: ", unit))
}
to_metres(5, "km"); to_metres(3, "mi")
# for loops: preallocate the result, then fill it by position.
balance <- numeric(5)
balance[1] <- 1000
for (year in 2:5) {
balance[year] <- balance[year - 1] * 1.04
}
round(balance, 2)
# while repeats until its condition is FALSE; next and break also work in for.
n <- 27; steps <- 0
while (n != 1) {
n <- if (n %% 2 == 0) n / 2 else 3 * n + 1
steps <- steps + 1
}
steps[1] "distinction"
[1] "absent"
[1] "pass" "not yet" NA "pass"
[1] 5000
[1] 4828.032
[1] 1000.00 1040.00 1081.60 1124.86 1169.86
[1] 111grade() checks is.na(score) first: if (NA >= 70) would be an error ("missing value where TRUE/FALSE needed"), because if cannot branch on an unknown. ifelse(), by contrast, simply passes the NA through. The final switch() argument has no name, so it is the default branch, here an error for unknown units. The balance loop is a case where a loop is natural, because each year depends on the previous one (though 1000 * 1.04^(0:4) would compute the same vector without a loop). The while loop follows the famous Collatz sequence from 27, which takes 111 steps to reach 1.
The apply family
Most loops in data analysis do the same thing to each element of a collection and gather the results. R has a family of functionals, functions that take a function as an argument, for exactly that:
| Function | Applies a function to | Returns |
|---|---|---|
lapply(x, f) | each element of a list or vector | a list |
sapply(x, f) | the same | a vector or matrix if possible, else a list |
vapply(x, f, template) | the same | a vector of the promised type and length, or an error |
Map(f, x, y) / mapply | elements of several vectors in parallel | a list (mapply simplifies) |
Filter(f, x) | each element | the elements where f is TRUE |
Reduce(f, x) | pairs, folding left to right | a single combined value |
apply(m, 1 or 2, f) | the rows (1) or columns (2) of a matrix | a vector or matrix |
tapply(x, group, f) | each group of x defined by group | a vector or array |
# lapply: apply a function to each element of a list (or vector); returns a list.
rainfall <- list(Arusha = c(64, 71, 120), Bergen = c(190, 152, 170, 140), Cusco = c(155, 140))
lapply(rainfall, mean)
# sapply simplifies the result to a vector when it can.
sapply(rainfall, length)
# vapply is sapply with a promise about the result type and length: safer in functions.
vapply(rainfall, function(x) max(x) - min(x), numeric(1))
# Several summaries per element: the result becomes a matrix.
sapply(rainfall, range)
# Map (mapply) walks along several vectors in parallel.
Map(function(name, x) paste(name, "had", length(x), "readings"), names(rainfall), rainfall)[[2]]
# Filter keeps elements for which a function returns TRUE; Reduce folds a list.
names(Filter(function(x) mean(x) > 130, rainfall))
Reduce(`+`, 1:5, accumulate = TRUE)
# apply works on the rows (1) or columns (2) of a matrix.
m <- matrix(c(3, 8, 1, 9, 4, 7), nrow = 2)
apply(m, 1, max)
apply(m, 2, sum)
# tapply: a function of one vector, split into groups by another.
tapply(mtcars$mpg, mtcars$cyl, mean)$Arusha
[1] 85
$Bergen
[1] 163
$Cusco
[1] 147.5
Arusha Bergen Cusco
3 4 2
Arusha Bergen Cusco
56 50 15
Arusha Bergen Cusco
[1,] 64 140 140
[2,] 120 190 155
[1] "Bergen had 4 readings"
[1] "Bergen" "Cusco"
[1] 1 3 6 10 15
[1] 4 9
[1] 11 10 11
4 6 8
26.66364 19.74286 15.10000(The rainfall figures are invented.) Notice how often the function passed in is written on the spot, without a name: function(x) max(x) - min(x) is an anonymous function. The backquoted `+` passes the addition operator itself as a function, since in R even operators are functions. And tapply(mtcars$mpg, mtcars$cyl, mean) answers "average fuel economy by number of cylinders" in one line, using the built-in mtcars data set of 1974 car models.
Which should you use? sapply is convenient at the console, but its result type depends on the data: if one element unexpectedly returns two values, you silently get a list or matrix instead of a vector. Inside functions that others will rely on, prefer vapply, which states the expected shape (numeric(1), "one number") and fails loudly if a result breaks the promise. The tidyverse's purrr package offers the same ideas with consistent names, such as map(), map_dbl() and map2().
The native pipe, short functions and closures
Nested calls read inside out: round(mean(faithful$waiting), 1) starts in the middle. The native pipe |>, added in R 4.1, turns this into a left-to-right sequence: x |> f(y) means f(x, y), so faithful$waiting |> mean() |> round(1) reads in the order things happen. In the same release R added \(x) as a short way to write function(x).
# The native pipe |> (R 4.1+) passes the value on its left as the first
# argument of the call on its right: x |> f(y) is f(x, y).
faithful$waiting |> mean() |> round(1)
# Pipelines read top to bottom, in the order things happen.
mtcars |>
subset(cyl == 4, select = c(mpg, wt)) |>
nrow()
# \(x) is short for function(x) (also R 4.1+): handy in pipes and apply calls.
sapply(1:5, \(n) n^2 + 1)
c(3.14159, 2.71828) |> (\(x) round(x, 2))()
# Functions are values: a function can build and return another function.
make_converter <- function(rate) {
function(amount) round(amount * rate, 2) # remembers 'rate': a closure
}
eur_to_kes <- make_converter(140.5) # an invented exchange rate
eur_to_kes(c(10, 25))
# <<- assigns to a variable in an enclosing scope; use it sparingly.
make_counter <- function() {
count <- 0
function() {
count <<- count + 1
count
}
}
tick <- make_counter()
tick(); tick(); tick()[1] 70.9
[1] 11
[1] 2 5 10 17 26
[1] 3.14 2.72
[1] 1405.0 3512.5
[1] 1
[1] 2
[1] 3The pipe always inserts the left-hand value as the first argument. When it needs to go elsewhere, R 4.1 requires a wrapper function, as in the awkward (\(x) round(x, 2))() above. Later versions added a placeholder, _, which must be used as a named argument (R 4.2 and later), and can also start a chain of extractions (R 4.3 and later). These are not available in R 4.1, so they are shown here without being run:
mtcars |> lm(mpg ~ wt, data = _) # R 4.2+: the data goes to the data argument
mtcars |> lm(mpg ~ wt, data = _) |> _$coefficients # R 4.3+: extract from the resultBefore 4.1, R users piped with %>% from the magrittr package, which the tidyverse loads, and you will see it in a great deal of existing code. It works much the same way; its placeholder is a dot (data = .). New code increasingly uses |>, which needs no package.
Closures
make_converter returns a function that remembers rate, the argument of the call that created it. A function together with the environment it was created in is called a closure, and R looks up variables lexically: first among the function's own arguments and local variables, then in the environment where the function was defined, then outwards. That is why eur_to_kes can still see rate after make_converter has returned. The counter uses <<-, which assigns to the nearest enclosing variable of that name instead of creating a local one; it is useful for small pieces of state like this, but code that uses it heavily is hard to follow.
When things go wrong
R has three kinds of condition a function can signal: an error with stop(), which ends the computation; a warning with warning(), which lets it continue but reports a problem; and a message with message(), purely informational. tryCatch() runs an expression and lets you handle each kind of condition with a function of your own, and its finally part runs whatever happens. Inside a function, on.exit() registers clean-up code that runs when the function ends, normally or by error.
# stop() signals an error; warning() a warning; message() a note.
safe_ratio <- function(a, b) {
if (!is.numeric(a) || !is.numeric(b)) stop("a and b must be numbers")
if (any(b == 0)) warning("division by zero gives Inf")
a / b
}
# tryCatch() runs code and handles conditions instead of stopping.
result <- tryCatch(
safe_ratio("5", 2),
error = function(e) {
cat("Caught an error:", conditionMessage(e), "\n")
NA
}
)
result
tryCatch(safe_ratio(1, 0),
warning = function(w) cat("Caught a warning:", conditionMessage(w), "\n"))
# finally runs whatever happens, like closing a file or a connection.
tryCatch({
cat("working...\n")
stop("something broke")
}, error = function(e) cat("handled:", conditionMessage(e), "\n"),
finally = cat("cleaning up\n"))
# Inside functions, on.exit() schedules clean-up code for when the function ends.
with_temp_file <- function() {
path <- tempfile(fileext = ".csv")
on.exit(unlink(path))
write.csv(data.frame(x = 1:3), path, row.names = FALSE)
nrow(read.csv(path))
}
with_temp_file()Caught an error: a and b must be numbers
[1] NA
Caught a warning: division by zero gives Inf
working...
handled: something broke
cleaning up
[1] 3The value of a tryCatch() call is the value of the expression, or, if a condition was caught, the value returned by its handler, which is how result became NA. Catching a warning with tryCatch stops the computation at the warning; to record a warning and carry on, R has withCallingHandlers() and suppressWarnings(), which you should use only when you have understood the warning.
Good practice in R is to fail early and clearly: check arguments at the top of a function with stopifnot() or stop() with a message that says what was expected, rather than letting a wrong input cause a puzzling error deep inside. Catch errors only where you can do something useful about them, such as skipping one bad file in a batch of a hundred and recording which one failed.
Misconception
"if (x > 5) checks every element of x." if needs exactly one TRUE or FALSE. Given a longer vector, R 4.2 and later raise an error ("the condition has length > 1"); older versions warned and used the first element. Decide what you mean: if (any(x > 5)), if (all(x > 5)), or a vectorised ifelse().
Functions the way experienced R programmers write them
A few conventions recur in well-maintained R code, from analysis scripts to CRAN packages:
- Small functions with clear names. A function should do one job that its name describes, usually a verb:
clean_names(),summarise_by_region(),fit_growth_model(). If you cannot name it, it probably does two jobs. - Inputs in, value out. Functions that take everything they need as arguments and return a result, without reading global variables or changing anything outside themselves, are easy to test and to reuse. Keep side effects (writing files, printing, plotting) in a few clearly named functions at the edges of a script.
- Explicit options. When an argument takes one of a few strings, list them in the default and let
match.arg()check the choice: withmethod = c("mean", "median")in the signature,method <- match.arg(method)accepts"median", defaults to"mean", and rejects"mode"with a helpful error. - Document as you go. Packages document each function with special comments above it, starting with
#', which the roxygen2 package turns into help pages; even in scripts, a line saying what the function returns, and in what units, saves time later. - Vectorise, then loop if you must. Write the body with vector operations so the function works on whole columns; reach for
vapplyor a loop only when each element genuinely needs separate treatment.
These habits pay off most when code is shared. An analysis is usually re-run months later, by a colleague or by yourself, on new data; functions with clear inputs and outputs are what make that painless. The next lessons use them constantly, and the professional lesson shows how to test them with the testthat package.
Exercises
1. Functions, control flow and the apply family
Warm-upComputationalWhat number does the last line print?
add_tax <- function(price, rate = 0.16) price * (1 + rate)
add_tax(rate = 0, 50)
2. Functions, control flow and the apply family
CoreComputationalWhat does this print? Write it with single spaces.
x <- c(4, 15, 9)
sapply(x, function(v) if (v > 5) v * 2 else v)
3. Functions, control flow and the apply family
Warm-upComputationalWhat does c(1, 4, 9, 16) |> sqrt() |> sum() print?
4. Functions, control flow and the apply family
CoreComputationalWhat does the last line print?
make_adder <- function(n) function(x) x + n
add3 <- make_adder(3)
n <- 100
add3(10)
5. Functions, control flow and the apply family
CoreComputationalWhat does this print?
total <- 0
for (i in 1:10) {
if (i %% 3 == 0) next
if (i > 7) break
total <- total + i
}
total
6. Functions, control flow and the apply family
StretchComputationalWhat does this print? Write the two lines separated by a single space.
r <- tryCatch({
warning("low battery")
"finished"
}, warning = function(w) "warned", finally = cat("done\n"))
r
7. Functions, control flow and the apply family
CoreHumanInside a function you are writing for colleagues, you need the number of rows of each data frame in a list dfs. Which call is the most robust?
Further reading and resources
- An Introduction to R, chapters 9 and 10: Control statements; Writing your own functions · R Core Team
- R documentation: Forward Pipe OperatorThe reference page for |>, including the placeholder rules of newer versions.
- Advanced R, chapters 6 to 9: Functions, Environments, Conditions, Functionals · Hadley Wickham
- R NEWS · R Core TeamWhat changed in each release, including the pipe in 4.1.0 and its placeholder in 4.2.0.