How to Chain If…Else Statements in R - dummies

How to Chain If…Else Statements in R

By Andrie de Vries, Joris Meys

In some cases, you will need to make multiple choices in R. The if and if…else statements leave you with exactly two options, but life is seldom as simple as that. Imagine you have some clients abroad.

Let’s assume that any client abroad doesn’t need to pay VAT for the sake of the example. This leaves you now with three different VAT rates: 12 percent for private clients, 6 percent for public clients, and none for foreign clients.

The most intuitive way to solve this problem is just to chain the choices. If a client is living abroad, don’t charge any VAT. Otherwise, check whether the client is public or private and apply the relevant VAT rate.

If you define an argument client for your function that can take the values ‘abroad’, ‘public’, and ‘private’, you could code the previous algorithm like this:

  tot.price <- net.price * 1.12      # 12% VAT
} else {
    tot.price <- net.price * 1.06    # 6% VAT
  } else {
    tot.price <- net.price * 1    # 0% VAT

With this code, you nest the second if…else statement in the first if…else statement. That’s perfectly acceptable and it will work, but imagine what you would have to do if you had four or even more possibilities. Nesting a statement in a statement in a statement in a statement quickly creates one huge curly mess.

Luckily, R allows you to write all that code a bit more clearly. You can chain the if…else statements as follows:

    tot.price <- net.price * 1.12
} else if(client=='public'){
    tot.price <- net.price * 1.06
} else {
    tot.price <- net.price

In this example, the chaining makes a difference of only two braces, but when you have more possibilities, it makes code readable. Note, that you don’t have to test whether the argument client is equal to ‘abroad’ (although it wouldn’t be wrong to do that). You just assume that if client doesn’t have any of the two other values, it has to be ‘abroad’.

Chained if…else statements work on a single value at a time. You can’t use these chained if…else statements in a vectorized way. For that, you can nest multiple ifelse statements, like this:

VAT <- ifelse(client=='private', 1.12,
          ifelse(client == 'public', 1.06, 1)
tot.price <- net.price * VAT

This piece of code can become quite confusing if you have more than three choices, though. The solution to this is to switch.