IF ELSE- ELSE IF Statement in R
IF ELSE- ELSE IF Statement in R, A developer’s best tool when trying to return output based on a condition is an if-else statement. The syntax in R is:
if (condition) { Expr1 } else { Expr2 }
How to Calculate Percentiles in R »
if else statement
If a variable named “quantity” is stored, we want to check if it is greater than 15. “Not Available” will be printed by the code if the quantity is more than 15. otherwise Available.
Now we can create a vector quantity
quantity <- 35
Let’s set the is-else statement
if (quantity > 15) { print('Not Available') } else { print('Available') }
[1] "Not Available"
Note: Be sure to indent each line properly. When the indentations are not in the proper place, code with several conditions can become unreadable.
How to use %in% operator in R »
The else-if clause
With the else if statement, we can further tailor the control level. You can add as many criteria as you like with elif. As for the syntax:
if (condition1) { expr1 } else if (condition2) { expr2 } else if (condition3) { expr3 } else { expr4 }
If we sold anything between 20 and 30, that would be interesting to know. If we do, the day will be the Average Day. If the amount exceeds 30, we print. What a wonderful day! else it wouldn’t be enough for today.
How to Set Axis Limits in ggplot2? »
As usual, create a vector quantity
quantity <- 15
Now we can create a multiple-condition statement
if (quantity <20) { print('Bad Day') } else if (quantity > 20 &quantity <= 30) { print('Average Day') } else { print('Good Day!') } [1] "Bad Day"
Example 2:
Depending on the product purchased, VAT is charged at a variable rate. Imagine that there are three different types of products with varying rates of VAT.
Categories | Products | VAT |
A | Books | 6% |
B | Vegetables | 9% |
C | Cloths | 12% |
To correctly apply the VAT rate to the item a customer purchased, we can create a chain.
category <- 'A' price <- 20 if (category =='A'){ cat('A vat rate of 6% is applied.','The total price is',price *1.08) } else if (category =='B'){ cat('A vat rate of 9% is applied.','The total price is',price *1.10) } else { cat('A vat rate of 12% is applied.','The total price is',price *1.20) }
A vat rate of 6% is applied. The total price is 21.6
Hope you clear about IF ELSE- ELSE IF Statement in R.
How to extract a time series subset in R? »