Module lessons (2/2)
Conditionals, Loops and Vectorization
Use if / else / ifelse(), safe for loops with seq_along(), while and understand when to prefer vectorized operations.
What you'll learn in this lesson
- Choose correctly between the scalar construct
if / elseand the vectorized functionifelse(). - Write safe
forloops avoiding the1:length(x)trap viaseq_along(). - Control repetitive conditions with
whilepreventing infinite loops. - Handle missing values
NAin logical tests and aggregate calculations (is.na(),na.rm = TRUE.
Overview
In R you have two distinct tools for making decisions: if (...) { ... } else { ... } evaluates a single true/false condition (for example to set the configuration of a script), while ifelse(test, yes, no) applies a choice on every element of a vector in one fell swoop.
The for (item in collection) loop iterates over the elements of a vector or list. However, when you need the numerical index of the position, always avoid 1:length(x): if x is empty (numeric(0)), 1:0 produces a sequence of 2 backward iterations (c(1, 0)) causing crashes or silent bugs! Use seq_along(x), which on an empty vector produces…
Sections covered in this lesson
- 1
if / elsevsifelse()vectorized - 2Safe
forandwhileloops - 3The missing values
NAand the logical flow - 4Test yourself: guided exercises
- 5Concept check
Unlock "Conditionals, Loops and Vectorization" and the full Course R curriculum
Use if / else / ifelse(), safe for loops with seq_along(), while and understand when to prefer vectorized operations.
Unlock all 7 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course R plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.