The &
(and
) and the |
(or
) operators are used to combine conditional statements in R
.
Conditional statements in R
programming are used to make decisions based on certain conditions.
In a simpler term, a conditional statement is a type of coding instruction used to compare values and expressions to make decisions.
"|"
operatorThe "|"
(or
) operator can be used to combine a conditional statement.
In the example below, we use the |
operator to combine conditional statements that will test if a variable value is greater or not greater than the others and vice versa.
# Creating our variablesx <- 200y <- 33z <- 500# using the | operator to combine conditional statementsif (x > y | z > x){print("Both conditions are true")}
x
, y
, and z
.if x > y
and if z > x
together using the |
operator by simplifying it to become if (x > y | z > x)
.true
.False
What happens when one of the given conditional statement(s) is incorrect?
Let’s look at the code below, where the value of the x
variable is greater than the y
variable, but we state otherwise.
# Creating our variablesx <- 200y <- 33z <- 500# using the | operator to combine conditional statementsif (x < y | z > x){print("One of the conditions is true")}
In the code above, despite a wrong statement, x < y
, the |
operator executes the code because the other statement provided, z > x
, is true
. However, the program will not execute when the conditional statements provided are all false
.
"&"
operatorThe "&"
(and
) operator can be used to combine a conditional statement.
In the example below, we use the &
operator to combine conditional statements that will test if a variable value is greater or not greater than the others and vice versa.
# Creating our variablesx <- 200y <- 33z <- 500# using the & operator to combine conditional statementsif (x > y & z > x){print("Both conditions are true")}
x
, y
, and z
.if x > y
and if z > x
together using the &
operator by simplifying it to become if (x > y & z > x)
.true
.False
What happens when one of the given conditional statement(s) is incorrect?
Let’s look at the code below where the value of thex
variable is greater than the y
variable, but we state it otherwise.
# Creating our variablesx <- 200y <- 33z <- 500# using the & operator to combine conditional statementsif (x < y & z > x){print("Both conditions are true")}else{print("False condition(s) provided!")}
In the code above, one of the provided conditional statements is wrong, and for that reason, the code cannot execute the command provided. This is not the same for the |
(or
) operator, in which if one condition is false
and the other is true
, the code will still execute.
|
operator, at least one condition must be true
.&
operator, the two conditions provided must be true
.