R Conditionals

if Statement

Basic Structure

if (condition) {
    // code block
}

Example

This block runs only if the condition inside the if is TRUE.

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

if-else Statement

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

Use else to specify an alternative action.

else if Ladder

Use multiple else if blocks to test a sequence of conditions.

x <- 5
if (x > 10) {
  print("x > 10")
} else if (x == 5) {
  print("x is exactly 5")
} else {
  print("x is something else")
}

Nested Conditionals

Nesting allows handling compound logic, but can reduce readability if overused.

x <- 10
if (x > 5) {
  if (x %% 2 == 0) {
    print("x is even and > 5")
  }
}

Vectorized Conditionals (ifelse)

ifelse() applies the condition across all elements in the vector.

ages <- c(15, 22, 17, 30)
status <- ifelse(ages >= 18, "Adult", "Minor")
print(status)

Best Practices

  • Use braces {} consistently for blocks, even if optional
  • Choose ifelse() over loops for element-wise logic
  • Keep conditional logic simple and readable

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic