if...else Statements
Let's build upon our concepts of the original if statements with the else statement.
We'll cover the following
What is an if...else
statement?
An if
statement can be followed by an optional else
statement, which executes when the conditional expression is FALSE
.
Let’s revisit our previous example. So now, we not only want to print “positive” when we encounter a positive number, but we also want to print “negative” when the number is not positive.
We have used the word not positive here to show that the
else
statement is executed whenever the original conditional statement is NOT satisfied.
Have a look at the modified illustration:
The above illustration can be mapped on to the following codes:
x <- 5if(x > 0) # condition for checking positive numbers (all positive numbers are greater than 0){print("Positive number")} else{print("Negative number")}
Let’s look at another example where the conditional statement checks whether the data in variable testNumber
is present in myVector
.
myVector <- c(1, 2, 3, 5)testNumber <- 4if(!testNumber %in% myVector){print("Not Found!")} else{print("Found")}
Nested if…else Statements
We can also nest one if...else
statement into another if...else
statement.
For example, if you are not older than or equal to years, you cannot vote. And if you are , you cannot vote if you don’t have a valid ID card. You can vote only if you are at least years old and have a valid ID card. Such a scenario can be easily demonstrated using a nested if...else
statement.
age <- 22validID <- TRUEif(age >= 18){if(validID){cat("voting is allowed")} else{cat("voting not allowed")}} else{cat("voting not allowed")}