R - Decision Making
R - Decision Making and Control Flow
Section titled “R - Decision Making and Control Flow”Decision-making structures are fundamental to any programming language. They allow a program to evaluate conditions and execute different blocks of code based on whether those conditions are true or false. This enables dynamic and responsive program behavior.
A typical decision structure first evaluates a logical condition. If the condition is TRUE, one or more statements are executed. Optionally, if the condition is FALSE, a different set of statements can be run. Modern R offers tools for both traditional program control flow and for efficient, vectorized conditional logic common in data analysis.
Traditional Control Flow
Section titled “Traditional Control Flow”These structures are used for controlling the script’s execution path. They are ideal for tasks like checking user input, handling errors, or directing program logic.
The if-else Statement
Section titled “The if-else Statement”An if statement executes a block of code if a condition is true. It can be paired with an else statement to provide an alternative block of code to run if the condition is false.
x <- -5
if (x > 0) { print("x is a positive number")} else if (x < 0) { print("x is a negative number")} else { print("x is zero")}The switch Statement
Section titled “The switch Statement”A switch statement provides a concise way to test a variable against a list of possible values, executing a different action for each.
operation <- "mean"data_vector <- c(10, 20, 30, 40, 50)
result <- switch(operation, "mean" = mean(data_vector), "sum" = sum(data_vector), "median" = median(data_vector), stop("Invalid operation specified") # Default case for no match)
print(paste("The", operation, "is:", result))Modern Conditional Logic for Data Analysis
Section titled “Modern Conditional Logic for Data Analysis”When working with data frames, performing conditional logic on entire columns is a common task. While you could use a loop with if-else, R provides much more efficient and readable vectorized functions for this purpose.
The dplyr::case_when() Function
Section titled “The dplyr::case_when() Function”case_when() is the modern, powerful, and recommended way to handle multiple conditions in a data analysis workflow. It is the tidyverse equivalent of a complex, nested if-else statement but is far more readable. It is typically used inside dplyr::mutate() to create a new column.
The syntax is condition ~ value, where condition is a logical test and value is the result to assign if that condition is met. case_when() evaluates conditions in order and stops at the first TRUE one.
# Load the necessary librarieslibrary(dplyr)library(tibble)
# Sample student datastudent_grades <- tibble( student_id = 1:6, score = c(95, 82, 75, 68, 89, 55))
# Use case_when() to create a new 'letter_grade' columngrades_with_letters <- student_grades |> mutate( letter_grade = case_when( score >= 90 ~ "A", score >= 80 ~ "B", score >= 70 ~ "C", score >= 60 ~ "D", .default = "F" # A safe way to specify a default value ) )
print(grades_with_letters)Executing this code cleanly adds a new column based on the specified logic:
# A tibble: 6 × 3 student_id score letter_grade <int> <dbl> <chr>1 1 95 A2 2 82 B3 3 75 C4 4 68 D5 5 89 B6 6 55 FWhich Should You Use?
Section titled “Which Should You Use?”Here’s a simple guide to choosing the right tool for the job.
| Statement | Primary Use Case |
|---|---|
if / else if / else | General program control flow. Handling single, non-vectorized conditions. Best for script logic, error handling, or function control. |
switch() | Simple dispatching based on the exact value of a single variable. Useful for routing to different functions. |
dplyr::case_when() | The preferred method for data manipulation. Use inside mutate() to create new columns in a data frame based on multiple, complex conditions. It is vectorized, readable, and robust. |