Next →

Output:


      

Plots:

Control Flow in R

Control flow statements allow your code to make decisions based on conditions. The most common control flow statements in R are if, else, and switch.

The if Statement

Executes code only if a condition is TRUE.

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

The if...else Statement

Provides an alternative action if the condition is FALSE.

x <- 3
if (x > 5) {
  print("x is greater than 5")
} else {
  print("x is not greater than 5")
}

The switch Statement

Useful for selecting one of many options.

day <- "Tuesday"
message <- switch(day,
  "Monday" = "Start of the week",
  "Tuesday" = "Second day of the week",
  "Wednesday" = "Midweek",
  "Unknown day"
)
print(message)

Control flow allows you to write more dynamic and flexible R scripts.