if...else Statements

Let's build upon our concepts of the original if statements with the else statement.

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:

Diagram to show code flow with if-else statement
Diagram to show code flow with if-else statement

The above illustration can be mapped on to the following codes:

x <- 5
if(x > 0) # condition for checking positive numbers (all positive numbers are greater than 0)
{
print("Positive number")
} else
{
print("Negative number")
}
Conditional statement is satisfied.

Let’s look at another example where the conditional statement checks whether the data in variable testNumber is present in myVector.

Press + to interact
myVector <- c(1, 2, 3, 5)
testNumber <- 4
if(!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 1818 years, you cannot vote. And if you are 1818, you cannot vote if you don’t have a valid ID card. You can vote only if you are at least 1818 years old and have a valid ID card. Such a scenario can be easily demonstrated using a nested if...else statement.

Press + to interact
age <- 22
validID <- TRUE
if(age >= 18)
{
if(validID)
{
cat("voting is allowed")
} else
{
cat("voting not allowed")
}
} else
{
cat("voting not allowed")
}