Control Flow in R

R BasicsControl StructuresFree Lesson

Advertisement

Introduction

Control flow structures allow you to control the execution of code based on conditions and iterate over sequences.

If-Else Statements

# Simple if
x <- 10
if (x > 5) {
  print("x is greater than 5")
}

# If-else
x <- 3
if (x > 5) {
  print("x is greater than 5")
} else {
  print("x is 5 or less")
}

# If-else if-else
x <- 5
if (x > 10) {
  print("x > 10")
} else if (x > 5) {
  print("x > 5 and <= 10")
} else {
  print("x <= 5")
}

Switch Statement

grade <- "A"

result <- switch(grade,
  "A" = "Excellent",
  "B" = "Good",
  "C" = "Average",
  "D" = "Poor",
  "F" = "Fail"
)
print(result)

For Loops

# Basic for loop
for (i in 1:5) {
  print(i)
}

# Loop through vector
fruits <- c("apple", "banana", "orange")
for (fruit in fruits) {
  print(fruit)
}

# Loop with index
for (i in seq_along(fruits)) {
  print(paste(i, fruits[i]))
}

While Loops

# While loop
i <- 1
while (i <= 5) {
  print(i)
  i <- i + 1
}

# Break and next
for (i in 1:10) {
  if (i == 3) next  # Skip iteration
  if (i == 7) break  # Exit loop
  print(i)
}

Apply Family

# lapply returns list
lst <- list(a = 1:3, b = 4:6)
lapply(lst, sum)

# sapply returns vector
sapply(lst, sum)

# apply for matrices
mat <- matrix(1:9, 3)
apply(mat, 1, sum)  # Row sums
apply(mat, 2, sum)  # Column sums

Summary

Control flow structures are essential for writing dynamic R code. Master these to handle complex logic.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement