5 Blocks, Loops, and Functions
By the end of this chapter you should be able to:
- Explain what a block of code is and how curly braces mark one.
- Use
ifandelseto run a block only when a test isTRUE. - Repeat a block with a
whileloop or aforloop, and avoid an infinite loop. - Decide when you need a loop and when a vectorized function already does the job.
- Write a function with one or more arguments, a default value, and a return value.
- 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 = 5assigns 5 tox. To ask “isxequal to 5?”, writex == 5.- The test must be one
TRUEorFALSE.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 vectorizedifelse()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.
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.
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) # 15.8 Check your understanding
In R, a block of code is marked by:
What is
xafter this code runs?x <- 10; if (x < 100) { x <- x + 1 }; if (x < 5) { x <- x - 1 }A
whileloop whose block never changes anything in its test will:A
forloop stops on its own after the last item in its vector.To test whether
xequals 5 inside anif, you writeif (x ___ 5). Fill in the blank.Which is the simplest way to add 1 to every element of a numeric vector
x?A function returns the value of the last line in its body, unless you use
return()earlier.After
numbers <- 10,addSeven <- function(numbers) { numbers + 7 }, andaddSeven(1), what isnumbers?
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.elsegives a second block forFALSE, andelse ifchains more tests. The test must be oneTRUEorFALSE; useifelse()for a whole vector. - A while loop repeats its block while its test is
TRUE. Something in the block must move the test towardFALSE, 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
- Predict, then run. Without running it, predict what this prints, then check:
x <- 1; while (x < 50) { x <- x * 2 }; x. - Grades. Write a function,
letterGrade(score), that usesif,else if, andelseto return"A"for 90 or more,"B"for 80 to 89,"C"for 70 to 79, and"F"below 70. Why doesletterGrade(c(95, 72))give an error? Rewrite it with nestedifelse()so that it works on a vector. - Loop or not? Write a
forloop that convertsc(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. - Running total. Use a
forloop to find the running total of births inc(1091, 487, 3188, 508, 1421): the first value, then the first two added up, and so on. Check your answer withcumsum(). - Checking inputs. Add an
ifstatement andstop()totoKm()so that it gives a helpful error whendistanceis negative. - 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 thatxandyare 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
ifandelse, 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.
{ }, that R runs as one
unit. if statements, loops, and functions each control a
block.
A loop that never ends because its test never becomes
FALSE. Stop it with Esc or RStudio’s red stop sign.
Done to every element of a vector at once, without a loop. Arithmetic in
R is vectorized, so distance / air_time divides row by row.
Code that takes inputs (arguments), does a job, and returns an output,
such as mean(temps).
An input to a function, written inside its parentheses.
The value an argument takes when you don’t supply one, set with
= in the function definition:
function(x, factor = 1.609).
What a function gives back. In R, it is the value of the last line in
the function’s body.
In R, a named piece of memory that holds data, such as
months <- 12. In a dataset, a measured characteristic,
such as median income; each Census variable has a code.
The integrated development environment (IDE) where you write and run R.
R does the computing; RStudio is the workspace around it.
The RStudio pane (bottom left) where R runs commands and prints results,
warnings, and errors. Nothing typed here is saved.
Code that runs a block only when a test is TRUE:
if (x < 5) { ... }. Add else { ... } for
when it is FALSE.
An operator that combines TRUE and FALSE
values: & (AND, both must be true), | (OR,
either can be true), and ! (NOT).
A sequence of values that R stores together, made with c(),
such as c(71, 75, 68).
A loop that repeats its block for as long as a test stays
TRUE. Something in the block must change the test, or it
never stops.
A loop that runs its block once for each item in a vector, such as
for (f in files) { ... }, then stops.
The variable in a for loop that takes the next item of the
vector on each pass, such as f in
for (f in files).
A plain-text table in which each line is a row and commas separate the
values. Read one into R with read.csv() or
read_csv().
The tidyverse package for transforming data frames: filtering rows,
choosing columns, adding new columns, joining tables, and summarizing.
The Census Bureau’s continuous survey of a sample of households every
year. It asks many more questions than the decennial census, but every
value is an estimate with a margin of error.
An R package that downloads US Census data through the Census API and
returns it as a tidy data frame, with boundaries attached if you ask.
A mean center in which each feature counts in proportion to an
attribute, such as population.
A closed shape that represents an area, such as a county, a lake, or a
census tract.
The geometric center of a polygon. st_centroid() in R.
An average in which some values count more than others. Total distance
divided by total air time weights each flight’s speed by its air time.
The private workspace R makes each time a function runs. Its arguments
and variables live there and vanish when it finishes.
Your main R workspace, where the variables you create at the Console or
in a script live. Functions don’t change it unless you assign their
result.
Which variables a piece of code can see. A function’s arguments are in
its own scope, separate from variables outside it.
The typical distance of features from their mean center: the spatial
counterpart of the standard deviation, drawn as a circle.