And / Or

Logical operators & (AND) and | (OR) are used to combine multiple conditions in an if...else statement. The AND operator returns TRUE if both conditions are true, while the OR operator returns TRUE if at least one condition is true.

# Using AND and OR operators
number <- 7
if (number > 5 & number < 10) {
    print("Number is between 5 and 10")
} else if (number > 10 | number < 5) {
    print("Number is either greater than 10 or less than 5")
} else {
    print("Number is 5 or 10")
}

Output:

[1] "Number is between 5 and 10"

Code Explanation: The AND operator & checks if number > 5 and number < 10, which is TRUE, so it prints "Number is between 5 and 10". The OR operator | is used in the second condition to check if number > 10 or number < 5.

Key Takeaways

  • AND (&) returns TRUE only if both conditions are TRUE.
  • OR (|) returns TRUE if at least one condition is TRUE.
  • Logical operators help in combining multiple conditions for decision-making.