R If...Else

The if...else statement in R is used for conditional execution of code. It checks a condition, and if the condition is TRUE, the code inside the if block is executed; otherwise, the code inside the else block is executed.

1. If...Else

An if statement evaluates a condition. If the condition is TRUE, the block of code inside the if is executed; otherwise, the block inside else is executed.

# If...Else example
number <- 10
if (number > 5) {
    print("Number is greater than 5")
} else {
    print("Number is not greater than 5")
}

Output:

[1] "Number is greater than 5"

Code Explanation: The condition number > 5 is TRUE, so the code inside the if block is executed, printing "Number is greater than 5".

Key Takeaways

  • The if statement executes code only if the condition is TRUE.
  • Use else to provide an alternative block of code if the condition is FALSE.
  • Conditions must evaluate to a logical value: TRUE or FALSE.