Rainbow Deals - hours only!Up to 80% off on all courses and bundles.-Close
Creating functions
If statements
14. else if statements


Great! Sometimes, you may need to consider more than just two conditions and execute a specific set of instructions for each case.

For example, let's say you've stored the age (an integer) of people in a variable named years and now want to categorize each person based on their age group:

  • young – years 0–24
  • adult – years 25–64
  • senior – years 65+

In R, we can do that with multiple if statements:

if (years >= 0 & years <= 24) {
} else if (25 <= years & years <= 64) { 
} else 

What's happening in this code? We've introduced the else if keyword. First, R checks if the given age is between 0 and 24. If it is, R prints "young"; if it isn't, we proceed to check if the age is between 25 and 64. The else clause gets executed only when all other conditions fail.


Now you try! Write a function named salary_category() that takes one argument (salary) and, based on its value, returns the proper category (string):

  • "low" if the average salary is less than or equal to 2500.
  • "medium" if the average salary is greater than 2500 but less than or equal to 4000.
  • "high" if the average salary is greater than 4000.