Chapter exercise: Blocks, Loops, and Functions
How Fast Are NC Cities Growing?
This exercise goes with Chapter 5, Blocks, Loops, and Functions. It builds on the R Basics (Chapter 3) and Indexing (Chapter 4) exercises. It should take you about one hour. Read this whole section before you start.
Download blocks-loops-functions-exercise.Rmd
Save it in a new folder called blocks-loops-functions-exercise inside your geog215 folder, open it in RStudio, and work through it from top to bottom. Everything on this page is also at the top of the file.
Purpose
Skills you’ll practice. By the end of this exercise you will be able to:
- Use
if,else if, andelseto run a block of code only when a test isTRUE. - Use
ifelse()to make the same decision for every element of a vector. - Repeat a block with a
whileloop, and keep it from running forever. - Repeat a block for each item in a vector with a
forloop, and save the results. - Decide when a loop is needed and when a vectorized function already does the job.
- Write your own functions, with arguments, default values, and a check that stops with a helpful error.
- Explain why a function doesn’t change the variables outside it.
Knowledge you’ll gain. You’ll estimate how many years it would take six North Carolina cities to double in size if they kept growing at their 2010 to 2020 rate, and sort the states into low, middle, and high income groups.
Why this matters. Real projects repeat the same steps many times: the same calculation for 100 counties, the same download for five years, the same map for every state. Copying and pasting code is slow and error-prone, because a fix in one copy doesn’t reach the others. Loops and functions let you write the steps once and reuse them, which is how analysts handle big data sets. You’ll also need to read functions: later in the course you’ll use functions that calculate the mean center and standard distance of a map layer, and they’re built from exactly the pieces you’ll practice today.
Task
Work through Parts 1 to 7 in order, top to bottom. In each part:
- Read the short explanation, then do each step marked with a bullet (•).
- Wherever you see
___, replace it with the missing code before you run the chunk. A chunk with___in it won’t run. - Before you run each chunk, predict what it will return. Then run it and check.
- Answer each question (Q1, Q2, …) in a sentence or two of Markdown, where it says Your answer here.
- If R seems stuck (the stop sign in the Console stays red), you’ve made an infinite loop. Click the stop sign or press Esc, then fix the loop.
| Part | What you’ll do | About |
|---|---|---|
| 1 | Set up your file and load the data | 3 min |
| 2 | Make decisions with if, else, and ifelse() |
12 min |
| 3 | Find a doubling time with a while loop |
10 min |
| 4 | Repeat a calculation with a for loop |
10 min |
| 5 | Write your own functions | 15 min |
| 6 | Put it all together: a loop that calls your function | 7 min |
| 7 | Reflect, knit, and turn in | 3 min |
Turn in your .Rmd file and your knitted .html file on Canvas.
Criteria for success
Use this checklist before you turn your work in. Each item matches a row of the rubric below.
| Criterion | Full credit | Partial credit | No credit |
|---|---|---|---|
| Knits (2 pts) | Knits to HTML; only the two error=TRUE chunks show errors |
Knits, but other chunks show errors | Doesn’t knit, or no HTML turned in |
| if/else and loops (5 pts) | Every blank filled in correctly; loops end and save their results | Most blanks correct, or a loop doesn’t save its results | Many blanks missing or wrong |
| Functions (5 pts) | All three functions return the test values; input check works | One function wrong, or no input check | Functions missing or don’t run |
| Questions (6 pts) | Q1 to Q12 answered correctly, with reasons | Some answers missing, wrong, or with no reason | Most answers missing |
| Style (1 pt) | Indented blocks, snake_case names, pipe where asked | Several problems | |
| Reflection (1 pt) | All three answered | Missing |
What a good answer looks like. Here is a question, a weak answer, and a strong one.
Question: Why didn’t the loop
while (x < 100) { y <- y + 1 }ever stop?Weak answer: “It was broken.”
Strong answer: “The test checks
x, but the block only changesy.xnever changes, sox < 100staysTRUEforever. The block has to changex, for example withx <- x + 1.”
The strong answer says which part of the code caused the problem, why, and how to fix it.
IMPORTANT! Save often. Before you knit, choose Run > Restart R and Run All Chunks to make sure every chunk works from a fresh start.
mean(temps).
The integrated development environment (IDE) where you write and run R.
R does the computing; RStudio is the workspace around it.
A sequence of values that R stores together, made with c(),
such as c(71, 75, 68).
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.
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).
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.
Data too large, fast, or varied for ordinary tools, often described by
three Vs: volume, velocity, and variety.
The average x coordinate and average y coordinate of a set of features.
Like the mean, outliers pull it.
The typical distance of features from their mean center: the spatial
counterpart of the standard deviation, drawn as a circle.
A block of R code inside an R Markdown file, starting with
```{r} and ending with three backticks.
A simple way of formatting plain text: # for headings,
*italic*, **bold**, and - for
list items.
The RStudio pane (bottom left) where R runs commands and prints results,
warnings, and errors. Nothing typed here is saved.
A loop that never ends because its test never becomes
FALSE. Stop it with Esc or RStudio’s red stop sign.
To build an R Markdown file into a finished document (HTML, PDF, or
Word). Knitting reruns every code chunk from the top in a fresh R
session.
A way of naming variables with lowercase words joined by underscores, as
in pop_chapel_hill. The tidyverse style guide uses it.
The operator |>, which passes the result on its left as
the first argument of the function on its right. Read it as “and then.”