4. Control Flow: if/else and for

Learn if/else branching and for loops in R with live, editable code.

if/else branches on a condition; for loops repeat code over a sequence. Loops are common in R, though vectorized code (like Lesson 2) is usually faster and more idiomatic.

Discuss first

Before you run the code below: grade_of() checks conditions top to bottom and stops at the first match. For a score of 82, which branch fires first โ€” >= 90, >= 80, or >= 70?

Edit the code below if you like, then press Run Code to check your answer.

Check your understanding

Q1. What does grade_of(71) return?

Q2. Fill in the blank: the loop keyword used to repeat code once per element of a sequence is:

(s in c(95, 82, 71, 40)) { ... }
Back to top