Week 5: Making Decisions in R

Learn to control the flow of your R scripts using conditional statements.

Explore Chapter 5

Chapter 5: Control Flow - Conditional Statements

Conditional Logic in R.

Often in programming, you need your code to make decisions and execute different actions based on whether certain conditions are met. This is called conditional logic or control flow.

In R, the primary tools for conditional execution are the `if`, `else if`, and `else` constructs. These allow your program to evaluate a condition (which results in a single `TRUE` or `FALSE` value) and choose which block of code to run accordingly.

Think of it like giving instructions: "If the temperature is below freezing, wear a heavy coat; otherwise, if it's cool, wear a jacket; otherwise, wear a t-shirt." R conditionals let you express similar logic in your code.

The `if` Statement.

The basic `if` statement executes a block of code only if a specified condition evaluates to `TRUE`.

Syntax

if (condition) {
  # Code block to execute if 'condition' is TRUE
  statement1
  statement2
  # ...
}
  • The `if` keyword is followed by the condition enclosed in parentheses `()`.
  • The condition must evaluate to a single `TRUE` or `FALSE`. Using a vector here will likely cause an error or a warning.
  • The code block to be executed is enclosed in curly braces `{}`. Even for a single statement, using braces is good practice for clarity.

Example

temperature <- 15

if (temperature < 20) {
  print("It's a bit cool outside.")
}

# This next block won't execute because the condition is FALSE
if (temperature > 30) {
  print("It's hot!")
}

`else if` and `else` Statements.

Often, you want to check multiple conditions or provide a default action if the initial `if` condition is false.

The `else` Statement

An `else` statement provides code to execute if the `if` condition is `FALSE`.

if (condition) {
  # Execute this if condition is TRUE
} else {
  # Execute this if condition is FALSE
}

The `else if` Statement

You can check additional conditions using `else if`. The conditions are checked sequentially. As soon as one condition (`if` or `else if`) is `TRUE`, its block is executed, and the remaining `else if` and `else` blocks are skipped.

if (condition1) {
  # Block 1: Executes if condition1 is TRUE
} else if (condition2) {
  # Block 2: Executes if condition1 is FALSE and condition2 is TRUE
} else if (condition3) {
  # Block 3: Executes if 1&2 are FALSE and condition3 is TRUE
} else {
  # Block 4: Executes if conditions 1, 2, and 3 are all FALSE
}

Example

score <- 75

if (score >= 90) {
  grade <- "A"
} else if (score >= 80) {
  grade <- "B"
} else if (score >= 70) {
  grade <- "C"
} else if (score >= 60) {
  grade <- "D"
} else {
  grade <- "F"
}

print(paste("The grade is:", grade)) # Output: [1] "The grade is: C"

The Vectorized `ifelse()` Function.

The standard `if`/`else` structure works great for single decisions based on one logical value. However, R often works with vectors, and you might want to apply a conditional choice element-wise based on a logical vector.

For this, R provides the `ifelse()` function, which is vectorized.

Syntax

ifelse(test_condition, value_if_true, value_if_false)
  • `test_condition`: A logical vector (or an expression that evaluates to one).
  • `value_if_true`: The value(s) to return for elements where `test_condition` is `TRUE`.
  • `value_if_false`: The value(s) to return for elements where `test_condition` is `FALSE`.

The `ifelse()` function evaluates the `test_condition` element by element. For each element, if the condition is `TRUE`, it returns the corresponding element from `value_if_true`; otherwise, it returns the corresponding element from `value_if_false`. R uses recycling rules if the lengths of the arguments differ.

Example

numbers <- -3:3 # Creates vector: -3 -2 -1  0  1  2  3
print(numbers)

# Classify numbers as "Positive" or "Non-positive"
classification <- ifelse(numbers > 0, "Positive", "Non-positive")
print(classification)
# Output: [1] "Non-positive" "Non-positive" "Non-positive" "Non-positive" "Positive" "Positive" "Positive"

# Calculate absolute value (alternative to abs())
absolute_values <- ifelse(numbers < 0, -numbers, numbers)
print(absolute_values)
# Output: [1] 3 2 1 0 1 2 3

Remember: Use `if`/`else if`/`else` for single decisions controlling which block of code executes. Use `ifelse()` for creating a new vector based on applying a condition element-wise to another vector.

Syllabus