Skip to main content
Module 2 · Lesson 2 of 24/18 in the course~20 min
Module lessons (2/2)

Conditionals, Loops and Vectorization

Lesson preview7 hands-on exercises readyCourse R · Module 2 — Data Frame and Flow

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 / else and the vectorized function ifelse().
  • Write safe for loops avoiding the 1:length(x) trap via seq_along().
  • Control repetitive conditions with while preventing infinite loops.
  • Handle missing values NA in 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. 1if / else vs ifelse() vectorized
  2. 2Safe for and while loops
  3. 3The missing values NA and the logical flow
  4. 4Test yourself: guided exercises
  5. 5Concept check
Pro Lesson · Module 2 — Data Frame and Flow

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.