Skip to main content

5  Blocks, Loops, and Functions

NoteLearning objectives

By the end of this chapter you should be able to:

  1. Explain what a block of code is and how curly braces mark one.
  2. Use if and else to run a block only when a test is TRUE.
  3. Repeat a block with a while loop or a for loop, and avoid an infinite loop.
  4. Decide when you need a loop and when a vectorized function already does the job.
  5. Write a function with one or more arguments, a default value, and a return value.
  6. Explain why a function’s arguments don’t change the variables outside it.

What is the first virtue of a programmer? Ingenuity? Grit? Devotion to R? Larry Wall, who created the Perl programming language, gave a surprising answer: laziness. He meant a particular kind of laziness: refusing to do the same work twice. A lazy programmer writes a piece of code once and reuses it, instead of typing (or copying and pasting) the same steps again and again.

This chapter covers the R tools that let you be productively lazy. Blocks group lines of code together. if statements decide whether a block runs, and loops decide how many times it runs. Functions, which you have been calling since Chapter 2, give a block a name so you can run it again with new inputs.

5.1 Blocks group lines of code

A block is the code between a pair of curly braces, { }. R reads everything from the opening brace to the matching closing brace and treats it as one unit:

All three lines run together, and R prints 10. On their own, braces don’t change much. Their power comes when you attach them to an if, a loop, or a function, which decide whether, or how many times, the block runs. A block either runs completely or is skipped completely.

Two habits make blocks easy to read:

  • Indent the lines inside a block by two spaces. RStudio does this for you when you press Enter after a {. The indentation shows at a glance where a block starts and ends.
  • Check your braces. Every { needs a matching }. A missing closing brace is one of the most common errors in R. When it happens, the Console shows a + prompt, because R is waiting for the rest of the block. Press Esc to start again.

The most common blocks are if statements, while loops, for loops, and functions. We’ll take them in that order.

5.2 if statements run a block only when a test is TRUE

An if statement has two parts: a test in parentheses and a block in braces. R works out the test. If it is TRUE, the block runs. If it is FALSE, R skips the whole block.

if (test) {
  # runs only when test is TRUE
}

Before you run the code below, predict the value of x at the end:

x starts at 10. Is 10 less than 100? Yes, so the first block runs and x becomes 11. Is 11 less than 5? No, so the second block is skipped. x ends at 11.

5.2.1 Adding else

Add else to give R a second block for when the test is FALSE. Exactly one of the two blocks runs:

You can chain tests with else if. R checks them from the top and runs the first block whose test is TRUE:

5.2.2 Writing good tests

The test uses the comparison and logical operators from Chapter 4: <, >, <=, >=, ==, !=, &, and |. Two mistakes come up again and again:

  • = is not ==. x = 5 assigns 5 to x. To ask “is x equal to 5?”, write x == 5.
  • The test must be one TRUE or FALSE. if (c(1, 8) > 5) is an error, because the test gives two answers, FALSE TRUE, and R doesn’t know which one to use. To decide something for every element of a vector, use the vectorized ifelse() instead:

5.3 while loops repeat a block while a test is TRUE

A while loop looks like an if statement, but instead of running its block once, it goes back to the test after every run. As long as the test is TRUE, the block runs again:

R checks the test (is 11 less than 100?), runs the block (x becomes 12), checks the test again, and so on. When x reaches 100 the test is FALSE and the loop stops, so x is 100.

WarningWatch out for infinite loops

The block must change something in the test, or the test never becomes FALSE and the loop never ends. If R seems stuck, click the red stop sign at the top of RStudio’s Console, or press Esc.

In practice, R users rarely write while loops. A for loop, or a function that works on a whole vector at once, is almost always simpler.

5.4 for loops run a block once for each item

A for loop doesn’t have a TRUE or FALSE test. Instead, it walks through a vector one item at a time. On each pass, the loop variable takes the next item:

On the first pass county is "Orange", on the second "Durham", and on the third "Wake". After the last item the loop stops on its own, so a for loop can’t run forever. That makes it safer than a while loop.

Use a for loop when you know what you want to repeat over: a set of files, counties, or years. This loop reads each CSV file in a folder and prints how many rows it has:

files <- list.files("data", pattern = "\\.csv$", full.names = TRUE)

for (f in files) {
  d <- read.csv(f)
  print(nrow(d))
}

5.4.1 Saving results from a loop

print() only shows a result. To keep the results, make an empty vector before the loop and fill in one element on each pass. seq_along() gives the positions 1, 2, 3, … of a vector, which makes a good loop variable:

5.4.2 Do you need a loop?

Many R functions are vectorized: they already work on every element of a vector at once. The loop above does the same job as one line:

Before you write a loop, check for a vectorized way to do the job. x + 1, sqrt(x), round(x), ifelse(), and the dplyr verbs you’ll meet in Unit 2 all work on whole vectors or columns. Reach for a loop when there isn’t one, such as reading many files or downloading data for many years.

TipThink about it

Later in the book, Chapter 13 downloads American Community Survey data with tidycensus. How could a for loop help you download the same table for 2019, 2020, 2021, 2022, and 2023, and save each year to its own file?

5.5 Functions name a block so you can reuse it

A function is a block with a name, inputs, and an output. You have already called many functions, such as mean(), round(), and read.csv(). Now that you know what a block is, you can write your own. Every function has the same parts:

name <- function(argument1, argument2) {
  # the body: a block of code
  result <- ...
  result          # the last value is the output
}
  • Name. You create a function the same way you create any object, with <-.
  • Arguments. The inputs, in parentheses after the word function. Inside the body they are placeholders for whatever you pass in.
  • Body. The block between the braces.
  • Return value. The value of the last line in the block is what the function returns. You can also write return(result) to make it explicit.

Here is the smallest useful function, addSeven(). Running the first three lines only creates the function; nothing is printed. The function runs when you call it:

Because + is vectorized, addSeven(c(1, 2, 3)) returns 8, 9, 10 without a loop.

5.5.1 A preview: the weighted mean center

In Chapter 17 you’ll use a function, meanCenter(), that finds the weighted mean center of a map layer. You don’t need to follow its spatial steps yet, but you can already pick out its parts. Its name is meanCenter, its arguments are layer and weights, its body turns polygons into centroids and takes the weighted mean of their coordinates, and its last line, mean_center, is the return value:

meanCenter <- function(layer, weights) {
  # convert the polygons into points
  points <- st_centroid(layer)
  # weighted mean of the x and y coordinates
  mc_x <- weighted.mean(st_coordinates(points)[, 1], weights)
  mc_y <- weighted.mean(st_coordinates(points)[, 2], weights)
  # create a point with the same CRS as the input layer
  mean_center <- st_sfc(st_point(c(mc_x, mc_y)))
  mean_center <- st_set_crs(mean_center, st_crs(layer))
  mean_center
}

mc_pop <- meanCenter(nc_counties, nc_counties$popE)

5.5.2 More than one argument, and defaults

Separate several arguments with commas. You can give an argument a default value with =. The function uses the default unless you pass something else:

5.5.3 Putting blocks inside functions

A function’s body can hold any block, including if statements and loops. A common use is to check the input and stop with a helpful message if it’s wrong. stop() ends the function with an error:

5.6 A function’s arguments are separate from variables outside it

What do these lines print? Predict, then run them:

addSeven(1) returns 8, and numbers is still 10. Inside the function, numbers means whatever you passed in, here 1. Each time a function runs, R gives it a fresh, private workspace, called its local environment, and throws that workspace away when the function finishes. The numbers in your own workspace, the global environment, is never touched.

This idea, which variables a piece of code can see, is called scope. It is why functions are safe to reuse: they don’t overwrite your variables unless you save their result with <-. If you want to keep what a function returns, assign it:

5.7 Your turn

Each of these only needs the pattern name <- function(input) { body }.

timesTwo <- function(x) {
  x * 2
}
timesTwo(c(1, 2, 3))          # 2 4 6

addThis <- function(numbers, amount) {
  numbers + amount
}
addThis(c(1, 2, 3), 10)       # 11 12 13

countAbove <- function(values, cutoff = 0) {
  sum(values > cutoff)
}
countAbove(c(-2, 5, 0, 8))    # 2
countAbove(c(-2, 5, 0, 8), 6) # 1

5.8 Check your understanding

  1. In R, a block of code is marked by:

  2. What is x after this code runs? x <- 10; if (x < 100) { x <- x + 1 }; if (x < 5) { x <- x - 1 }

  3. A while loop whose block never changes anything in its test will:

  4. A for loop stops on its own after the last item in its vector.

  5. To test whether x equals 5 inside an if, you write if (x ___ 5). Fill in the blank.

  6. Which is the simplest way to add 1 to every element of a numeric vector x?

  7. A function returns the value of the last line in its body, unless you use return() earlier.

  8. After numbers <- 10, addSeven <- function(numbers) { numbers + 7 }, and addSeven(1), what is numbers?

5.9 Summary

  • A block is code inside curly braces { } that R runs as one unit. Indent it, and match every { with a }.
  • An if statement runs its block only when its test is TRUE. else gives a second block for FALSE, and else if chains more tests. The test must be one TRUE or FALSE; use ifelse() for a whole vector.
  • A while loop repeats its block while its test is TRUE. Something in the block must move the test toward FALSE, or the loop never ends.
  • A for loop runs its block once for each item in a vector, then stops. Fill a vector made before the loop to keep the results.
  • Many R functions are vectorized, so check for one before you write a loop.
  • A function is a named block: name <- function(arguments) { body }. The last line is the return value. Arguments can have default values.
  • A function’s arguments live in its own local environment, so a function never changes your variables unless you assign its result.

5.10 Exercises

  1. Predict, then run. Without running it, predict what this prints, then check: x <- 1; while (x < 50) { x <- x * 2 }; x.
  2. Grades. Write a function, letterGrade(score), that uses if, else if, and else to return "A" for 90 or more, "B" for 80 to 89, "C" for 70 to 79, and "F" below 70. Why does letterGrade(c(95, 72)) give an error? Rewrite it with nested ifelse() so that it works on a vector.
  3. Loop or not? Write a for loop that converts c(32, 50, 68, 86, 104) from degrees Fahrenheit to Celsius, (f - 32) * 5 / 9, and stores the results. Then do the same thing in one line without a loop.
  4. Running total. Use a for loop to find the running total of births in c(1091, 487, 3188, 508, 1421): the first value, then the first two added up, and so on. Check your answer with cumsum().
  5. Checking inputs. Add an if statement and stop() to toKm() so that it gives a helpful error when distance is negative.
  6. Standard distance again. (Come back to this one after Chapter 17.) Chapter 17’s standardDistance(x, y) function returns the standard distance of a set of points. Add a check that x and y are the same length, and stop with a message if they aren’t.

5.11 Further reading

  • R for Data Science (2nd ed.), by Hadley Wickham, Mine Çetinkaya-Rundel, and Garrett Grolemund, free at https://r4ds.hadley.nz. The “Functions” and “Iteration” chapters show more ways to write functions and to avoid loops.
  • Hands-On Programming with R, by Garrett Grolemund, free at https://rstudio-education.github.io/hopr/. Its chapters on if and else, loops, and environments go further into the ideas in this chapter.
  • Programming Perl (3rd ed.), by Larry Wall, Tom Christiansen, and Jon Orwant (O’Reilly, 2000), where Wall describes the three virtues of a programmer: laziness, impatience, and hubris.