IF, ELSE, ELSE IF Statement in R

The if else statement

An if-else statement is a great tool for the developer trying to return an output based on a condition. In R, the syntax is:

if (condition) {
} else {

If Else Statement

We want to examine whether a variable stored as “quantity” is above 20. If quantity is greater than 20, the code will print “You sold a lot!” otherwise Not enough for today.

# Create vector quantity
quantity <-  25
# Set the is-else statement
if (quantity > 20) {
    print('You sold a lot!')
} else {
    print('Not enough for today')  


## [1] "You sold a lot!"

Note: Make sure you correctly write the indentations. Code with multiple conditions can become unreadable when the indentations are not in correct position.

The else if statement

We can further customize the control level with the else if statement. With elif, you can add as many conditions as we want. The syntax is:

if (condition1) { 
    } else if (condition2) {
    } else if  (condition3) {
    } else {

We are interested to know if we sold quantities between 20 and 30. If we do, then the pint Average day. If quantity is > 30 we print What a great day!, otherwise Not enough for today.

You can try to change the amount of quantity.

# Create vector quantiy
quantity <-  10
# Create multiple condition statement
if (quantity <20) {
      print('Not enough for today')
} else if (quantity > 20  &quantity <= 30) {
     print('Average day')
} else {
      print('What a great day!')


## [1] "Not enough for today"

Example 2:

VAT has different rate according to the product purchased. Imagine we have three different kind of products with different VAT applied:

Categories Products VAT
A Book, magazine, newspaper, etc.. 8%
B Vegetable, meat, beverage, etc.. 10%
C Tee-shirt, jean, pant, etc.. 20%

We can write a chain to apply the correct VAT rate to the product a customer bought.

category <- 'A'
price <- 10
if (category =='A'){
  cat('A vat rate of 8% is applied.','The total price is',price *1.08)  
} else if (category =='B'){
    cat('A vat rate of 10% is applied.','The total price is',price *1.10)  
} else {
    cat('A vat rate of 20% is applied.','The total price is',price *1.20)  


# A vat rate of 8% is applied. The total price is 10.8