How to Loop Through Values in R

Sometimes when making choices using R, you can use only a single value to base your choice on. You could apply that code on each value you have by hand, but it makes far more sense to automate this task.

Construct a for loop

As in many other programming languages, you repeat an action for every value in a vector by using a for loop. You construct a for loop in R as follows:

for(i in values){
... do something ...
}

This for loop consists of the following parts:

The keyword for, followed by parentheses.

An identifier between the parentheses. In this example, we use i, but that can be any object name you like.

The keyword in, which follows the identifier.

A vector with values to loop over. In this example code, we use the object values, but that again can be any vector you have available.

A code block between braces that has to be carried out for every value in the object values.

In the code block, you can use the identifier. Each time R loops through the code, R assigns the next value in the vector with values to the identifier.

Calculate values in a for loop

Let’s take another look at the priceCalculator() function. Earlier, we show you a few possibilities to adapt this function so you can apply a different VAT rate for public, private, and foreign clients. You can’t use any of these options in a vectorized way, but you can use a for loop so the function can calculate the price for multiple clients at once.

The first and the last part of the function haven’t changed, but in the middle section, you do the following:

Create a numeric vector with length 0 and call it VAT.

For every value in the vector client, apply switch() to select the correct amount of VAT to be paid.

In each round through the loop, add the outcome of switch() at the end of the vector VAT.

The result is a vector VAT that contains, for each client, the correct VAT that needs to be applied. You can test this by adding, for example, a variable type to the data frame clients you created in the previous section like this: