R If OR

R If statement has a condition which evaluates to a boolean value, and based on this value, it is decided whether to execute the code in if-block or not. Now, this condition can be a simple condition or a compound condition. A compound condition is formed by joining simple conditions using logical operators.

In this tutorial, we will learn how to use logical OR operator || in R If statement.

Syntax

The syntax to use logical OR operator in if-statement to join two simple conditions: condition1 and condition2 is

if(condition1 || condition2){
     #code
 }

The overall condition becomes TRUE if any of condition1 or condition2 is TRUE.

The truth table for different values of simple conditions joined with OR operator is

condition1condition2condition1 && condition2
TRUETRUETRUE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
ADVERTISEMENT

Examples

In the following program, we take a value in x, and check if this value is even number or is divisible by 5. Now, there are two simple conditions here. The first is if x is an even number. The second is if x is divisible by 5. We need a condition to check if at least one of these two conditions is TRUE. Therefore, we shall use OR operator to join these simple conditions in our IF statement.

example.R

x <- 10
if (x%%2 == 0 || x%%5 == 0) {
   print("x is even OR x is divisible by 5.")
}

Output

[1] "x is even OR x is divisible by 5."

Now, let us take another value for x, where both the conditions are FALSE.

example.R

x <- 9
if (x%%2 == 0 || x%%5 == 0) {
   print("x is even OR x is divisible by 5.")
}
print("end of program")

Since, the whole if-condition evaluates to FALSE, the code inside if-block does not execute.

Output

[1] "end of program"

Conclusion

In this R Tutorial, we learned how to use logical OR operator in IF statement in R Programming language, with the help of example programs.