DS 3: Control Flow

Week 3 · Tuesday, Oct 13 · 9:50-10:55 am · Self-guided

Dr. Marcela Alfaro Córdoba

Goal for this morning

Work through one lesson on the Intro to R site, on your own:

By 10:55 you should have one proof-of-completion PDF downloaded, and a script that re-runs your work in Positron.

Important

3 points, as always: 2 for the printout, 1 for the discussion check, this time on Tuesday, Oct 20, 1:30 pm.

Ground rules

Allowed

  • The R help pages: ?, ??, apropos()
  • The lesson page itself
  • Thursday’s slides
  • Your own notes and scripts
  • Asking me

Not allowed

  • ChatGPT, Claude, Copilot, Gemini, any chatbot
  • Positron Assistant or inline suggestions
  • Copying a classmate’s code

Talking through an idea with a neighbor is fine. Reading their screen and typing what’s on it is not.

Before every loop: trace it by hand

Run the first two steps on paper, then run the code.

For a loop, write down what the loop variable holds and what the result looks like after step 1 and step 2:

# step   cont        m      verdict
#  1     "Africa"    48.9   c(Africa = "below")
#  2     "Americas"  64.7   c(Africa = "below", Americas = "above")

Note

The discussion check (Tuesday, Oct 20) will ask you to do exactly this on a loop from your own printout, without a laptop.

Work in a script, not just the browser

Open stat266a in Positron and create week03/ds03_notes.R:

# DS 3 · Control flow · my notes
source("scripts/load-gapminder.R")
source("scripts/check-gapminder.R")

# Exercise 1 ---------------------------------------------------------
# My y1, y2 were:
# I predict:
  • For each exercise, copy your final answer from the browser into this script, under its heading
  • Run it on the full gapminder data. The lesson uses a smaller piece, gm. Do you get what you expected?
  • Write your hand traces as comments

Tip

The browser forgets your work if the cache clears. Your script doesn’t. And at 10:50, the restart test: Session → Restart R, source week03/ds03_notes.R, and it should run to the end.

How to work

  1. Read the lesson section above the exercises first
  2. Click Run in the exercise box to see your seeded values
  3. Trace the first two steps on paper. Write it as a comment
  4. Write your code. Check. If it fails, read the message before changing anything
  5. Copy the working version into week03/ds03_notes.R

If you spend more than 10 minutes on one exercise, raise your hand. Being stuck is useful; being stuck for 40 minutes is not.

Lesson 6: Control Flow

What you’re practicing

Exercise The skill
1. Is that year in the data? if/else with any(); the one-line if
2. Grow vs. fill Pre-allocating, and computing a position in a nested loop
3. Continents above or below Looping over groups, storing results in a named vector
4. Three bands per country if / else if / else inside a loop
5. Advanced: flag some countries Two conditions with &&, collecting matches

Exercises 3 and 4 are the core of the lesson and the ones we discuss on Tuesday, Oct 20. Exercise 5 is the hardest. Do it last.

Tips: Exercises 1 and 2

Exercise 1. gm$year == y1 is a whole vector of TRUE/FALSE. if needs one value. Which of any() or all() answers “are there any rows from that year”?

Use y1 and y2, not the years you saw printed. The check runs with different values.

Exercise 2. Before writing code, fill in this table by hand for your n_inner:

i j value i * 10 + j position in filled
1 1 11 1
1 2 12 2
2 1 21 ?

The ? is the whole exercise. It depends on n_inner, not on n_outer.

Tips: Exercises 3 and 4

Exercise 3. Thursday’s “storing one result per group” slide is almost the answer, with two differences: gm$continent is a factor, so loop over levels(); and the cutoff is yours, in cutoff.

Check with length(verdict): one entry per continent, and names(verdict) should be the continents.

Exercise 4. Inside the loop, first pull out one number: that country’s 2007 life expectancy. Print it for the first country to make sure it’s one number, not a vector.

le <- gm$lifeExp[gm$country == ctry & gm$year == 2007]

Then the bands. Re-read the boundaries: "mid" includes lo and excludes hi. Which comparison is < and which is <=?

Tips: Exercise 5

Break it into pieces and test each one outside the loop first, on one country you pick:

ctry <- levels(gm$country)[1]
startsWith(ctry, letter)                          # TRUE or FALSE?
mean(gm$lifeExp[gm$country == ctry])              # one number?

Then combine the two with &&, inside the loop. Collect matches by growing: flagged <- c(flagged, ctry).

Extra, in your script: for each flagged country, plot(year, lifeExp, type = "l") using the full gapminder data. Put the plotting loop in week03/ds03_notes.R too.

Halfway check: 10:25

By now you should be done with Exercises 1 and 2 and working on 3.

Behind? That’s fine. Priorities:

  1. Exercises 3 and 4, the ones we discuss on Tuesday, Oct 20
  2. Exercise 1
  3. Exercises 2 and 5, tonight if needed

Done early? Walk over to someone who’s stuck and ask them to trace their loop for you, out loud. Don’t tell them the answer.

Finishing up

Get your PDF

At the bottom of the lesson page:

  1. Make sure your name is filled in on the site
  2. Attempt every exercise (an honest wrong attempt counts)
  3. Click Download my proof-of-completion PDF

Warning

Do it now, in the room. The site stores your work in your browser: a cleared cache or a different laptop and it’s gone. Your week03/ds03_notes.R is your backup.

What to submit and bring

Upload to Canvas by Wednesday 11:59 pm

  • The PDF

Bring to Tuesday, Oct 20, 1:30 pm

  • The PDF, printed on paper
  • A pencil

Late: up to 3 days, 5% off per 24 hours. The lowest DS grade is dropped.

Before you go: checklist

See you at 1:30 pm for Cleaning data in practice. Before then, download the dataset we’ll clean into your data/ folder: field_survey.csv (right-click → Save link as…).