Skip to main content

4  Functions, Decisions, and Loops

So far you have used functions other people wrote: sqrt(), mean(), seq(). This chapter covers writing your own, and the two other pieces of programming every language has: doing different things depending on a condition, and doing something repeatedly. R needs the last two less often than you might expect.

4.1 Writing a function

The period of a simple pendulum of length \(L\) is \(T = 2\pi\sqrt{L/g}\). You could type that formula every time you need it. It is better to type it once and give it a name:

pendulum_period <- function(length_m) {
  2 * pi * sqrt(length_m / 9.81)
}

pendulum_period(1)
#> [1] 2.006067

A one-meter pendulum takes almost exactly two seconds per full swing.

The pieces: function(length_m) says “this is a function with one argument called length_m”. The code between the braces is the body. When you call pendulum_period(1), R runs the body with length_m set to 1, and the value of the last line is what comes back. The <- stores the function under a name, the same way it stores a number.

Functions can take several arguments:

kinetic_energy <- function(mass_kg, speed_m_s) {
  0.5 * mass_kg * speed_m_s^2
}

kinetic_energy(0.145, 40)
#> [1] 116

That is a 145 g baseball at 40 m/s: 116 J.

4.2 Default arguments

Hard-coding 9.81 inside pendulum_period() means the function only works on Earth. Make g an argument instead, and give it a default value:

pendulum_period <- function(length_m, g = 9.81) {
  2 * pi * sqrt(length_m / g)
}

pendulum_period(1)
#> [1] 2.006067
pendulum_period(1, g = 1.62)
#> [1] 4.936537

Leave g out and you get Earth. Supply it and you get somewhere else, here the Moon, where the same pendulum takes about 4.9 s. Built-in functions work the same way, which is why you can call them with one or two arguments even when the help page lists ten.

4.3 Vectorized for free

Nothing in pendulum_period() mentions vectors. But the arithmetic inside it is the vectorized arithmetic of Chapter 3, so the function accepts a vector without any extra work:

lengths_m <- seq(0.2, 1.0, by = 0.2)
pendulum_period(lengths_m)
#> [1] 0.8971403 1.2687480 1.5538926 1.7942806 2.0060667

Five lengths in, five periods out. The same goes for a slightly longer function, the projectile range \(R = v^2 \sin(2\theta)/g\) from Chapter 2:

projectile_range <- function(speed_m_s, angle_deg, g = 9.81) {
  angle_rad <- angle_deg * pi / 180
  speed_m_s^2 * sin(2 * angle_rad) / g
}

projectile_range(20, angle_deg = c(15, 30, 45, 60, 75))
#> [1] 20.38736 35.31194 40.77472 35.31194 20.38736

The range peaks at 45 degrees, and 30 and 60 degrees give the same answer, as they should. The conversion to radians from Chapter 2 is the kind of detail worth burying in a function: get it right once and stop thinking about it.

angle_rad exists only while the function is running. Variables created inside a function are invisible outside it, so they cannot collide with something of the same name in your script. A function can see variables defined outside it, but relying on that is a common source of bugs. Pass in everything the function needs as arguments.

One more tool for functions you will reuse: stopifnot() halts with an error if a condition is false. Putting stopifnot(length_m > 0) on the first line of pendulum_period() turns a negative length into an immediate error, instead of a NaN (“not a number”) that surfaces three steps later.

4.4 Decisions

if runs code only when a condition is true, and else covers the other case. Earth’s escape speed at the surface is about 11.2 km/s:

escape_speed_m_s <- 11186
speed_m_s <- 9000

if (speed_m_s >= escape_speed_m_s) {
  "escapes"
} else {
  "falls back"
}
#> [1] "falls back"

The condition in parentheses must be a single TRUE or FALSE. Give if a vector of speeds and it refuses:

speeds_m_s <- c(3000, 9000, 12000, 17000)

if (speeds_m_s >= escape_speed_m_s) "escapes" else "falls back"
#> Error in `if (speeds_m_s >= escape_speed_m_s) ...`:
#> ! the condition has length > 1

For a vector, the tool is ifelse(). It takes a logical vector, a value to use where it is TRUE, and a value to use where it is FALSE, and it makes the choice element by element:

ifelse(speeds_m_s >= escape_speed_m_s, "escapes", "falls back")
#> [1] "falls back" "falls back" "escapes"    "escapes"

The division of labor: if controls which code runs, and usually lives inside functions. ifelse() computes a vector of values, so it also works on a column of data.

4.5 Loops

A for loop runs its body once for each element of a vector. This one computes the pendulum periods the slow way:

periods_s <- numeric(length(lengths_m))

for (i in seq_along(lengths_m)) {
  periods_s[i] <- pendulum_period(lengths_m[i])
}

periods_s
#> [1] 0.8971403 1.2687480 1.5538926 1.7942806 2.0060667

numeric(5) makes a vector of five zeros, so the results have somewhere to go. Create the full-length vector before the loop and fill it in, because growing a vector one element at a time is slow. seq_along(lengths_m) is the vector 1, 2, 3, 4, 5, one index per element, and i takes each of those values in turn. You will also see 1:n written for the same purpose.

You have already seen the better way to get this result: pendulum_period(lengths_m), one line, no loop, no index to get wrong. If you come from Python or C, the loop will be the first thing you reach for. In R it should be the second.

A while loop repeats for as long as a condition holds, which suits problems where you do not know the number of steps in advance. Drop a ball from 1 m, and suppose each bounce returns it to 80% of its previous height. Count the bounces until it rises less than a centimetre:

height_m <- 1
bounces <- 0

while (height_m >= 0.01) {
  height_m <- 0.8 * height_m
  bounces <- bounces + 1
}

bounces
#> [1] 21

It takes 21 bounces. A while loop whose condition never becomes false runs forever. The Esc key gets you out.

TipWhen to loop

Try vectorized code first. Use a loop when step \(n\) depends on the result of step \(n - 1\), so the steps cannot all be done at once. That rule covers nearly every case you will meet in a physics course.

R also has functions that apply a function to each element of a vector and collect the results: sapply() in base R and map() in the tidyverse’s purrr package. You do not need them yet.

4.6 A loop that earns its place

Here is a case where each step really does depend on the one before. A ball falls from rest through air, with a drag force proportional to its speed, \(F_{\mathrm{drag}} = -bv\). Taking down as positive, Newton’s second law gives its acceleration:

\[ \frac{dv}{dt} = g - \frac{b}{m}v \]

The acceleration depends on the current speed, which depends on all the acceleration up to that moment. The simplest way through is to take small steps in time. Over a short interval \(\Delta t\) the acceleration barely changes, so the new speed is the old speed plus acceleration times \(\Delta t\). This is called an Euler step.

mass_kg <- 0.5
b_kg_s <- 0.5
g <- 9.81
dt_s <- 0.01
n <- 1001

v_m_s <- numeric(n)
for (i in 2:n) {
  accel_m_s2 <- g - (b_kg_s / mass_kg) * v_m_s[i - 1]
  v_m_s[i] <- v_m_s[i - 1] + accel_m_s2 * dt_s
}

v_m_s[c(1, 101, 301, 1001)]
#> [1] 0.000000 6.219223 9.328909 9.809576

The vector starts as all zeros, so v_m_s[1], the speed at \(t = 0\), is already correct: the ball starts at rest. The loop begins at 2 and fills in each speed from the one before it. The four values printed are the speeds at 0, 1, 3, and 10 s.

The ball speeds up quickly at first, then less and less, as drag grows to balance gravity. Setting the acceleration to zero in the equation above gives the terminal speed, \(v_t = mg/b\):

mass_kg * g / b_kg_s
#> [1] 9.81
v_m_s[n]
#> [1] 9.809576

After ten seconds the simulated ball is within 0.0005 m/s of the terminal speed the formula predicts.

A four-line loop has solved a differential equation numerically. Chapter 10 builds this idea up properly: position as well as velocity, a better step than Euler’s, and plots of the result. Before that, lab data needs somewhere to live. Chapter 5 introduces the data frame, R’s table.