Course
Live Selenium Webdriver Testing Project: Join FREE
Project Summary This project will put you in an Online Corporate Test Environment. You will be...
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) {
Expr1
} else {
Expr2
}
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')
}
Output:
## [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.
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) {
expr1
} else if (condition2) {
expr2
} else if (condition3) {
expr3
} else {
expr4
}
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!')
}Output:
## [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)
}Output:
# A vat rate of 8% is applied. The total price is 10.8
Project Summary This project will put you in an Online Corporate Test Environment. You will be...
DVD players are software that allows you to view videos on PC using a DVD-ROM drive. You can use...
Download PDF 1) What Is SDLC? SDLC is an abbreviation of Software Development Life Cycle. SDLC is...
Music visualizers are software that can generate animated imagery that follows loudness, frequency spectrum,...
Video converter is used when you cannot open a video of a certain format. It is also used when you...
What is CRM? CRM stands for “Customer Relationship Management” and is a set of methodologies and...