How to Switch Between Possibilities with If…Else Statements in R

At times, it is useful to switch between possibilities in R. The nested if...else statement is especially useful if you have complete code blocks that have to be carried out when a condition is met. But if you need to select values based only on a condition, there’s a better option: Use the switch() function.

Make choices with switch

When making choices with switch, you have a list of three possible choices, and for each choice you have a specific VAT rate. You can use the switch() function like this:

VAT <- switch(client, private=1.12, public=1.06, abroad=1)

You construct a switch() call as follows:

  1. Give a single value as the first argument (in this case, the value of client).

    Note that switch() isn’t vectorized, so it can’t deal with vectors as a first argument.

  2. After the first argument, you give a list of choices with the respected values.

    Note that you don’t have to put quotation marks around the choices.

Remember that switch() doesn’t work in a vectorized way. You can distinguish the choices more easily, however, so the code becomes more readable.

In fact, the first argument doesn’t have to be a value; it can be some expression that evaluates to either a character vector or a number. In case you work with numbers, you don’t even have to use choice=value in the function call. If you have integers, switch() will return the option in that position. In the statement switch(2,'some value', 'something else', 'some more'), the result is 'something else'.

Use default values in switch

You don’t have to specify all options in a switch() call. If you want to have a certain result in case the matched value is not among the specified options, put that result as the last option, without any choice.

VAT <- switch(client, private=1.12, public=1.06, 1)

You can easily test this out in the console by creating an object called client with a certain value and then running the switch() call, as in the following example:

> client <- 'other'
> switch(client, private=1.12, public=1.06, 1)
[1] 1

You can give client different values to see how switch() works.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.