Nested If

A nested if statement is an if...else statement inside another if...else. It allows for checking multiple conditions in a hierarchical manner.

# Nested If example
number <- 15
if (number > 10) {
    print("Number is greater than 10")
    if (number > 20) {
        print("Number is also greater than 20")
    } else {
        print("Number is not greater than 20")
    }
} else {
    print("Number is not greater than 10")
}

Output:

[1] "Number is greater than 10"
[1] "Number is not greater than 20"

Code Explanation: The outer if checks if number > 10, which is TRUE, so it prints "Number is greater than 10". The inner if then checks if number > 20, which is FALSE, so it prints "Number is not greater than 20".

Key Takeaways

  • Nested if statements allow for checking multiple conditions.
  • Each if can have its own else block.
  • Indentation and proper formatting help in understanding nested structures.