Skip to main content

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.

TipGet the exercise file

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:

  1. Use if, else if, and else to run a block of code only when a test is TRUE.
  2. Use ifelse() to make the same decision for every element of a vector.
  3. Repeat a block with a while loop, and keep it from running forever.
  4. Repeat a block for each item in a vector with a for loop, and save the results.
  5. Decide when a loop is needed and when a vectorized function already does the job.
  6. Write your own functions, with arguments, default values, and a check that stops with a helpful error.
  7. 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 changes y. x never changes, so x < 100 stays TRUE forever. The block has to change x, for example with x <- 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.