How to Loop Through Values in R - dummies

How to Loop Through Values in R

By Andrie de Vries, Joris Meys

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.

Use the values of the vector

Adapt the priceCalculator() function as follows:

priceCalculator <- function(hours, pph=40, client){
    net.price <- hours * pph *
                   ifelse(hours > 100, 0.9, 1)
    VAT <- numeric(0)
    for(i in client){
      VAT <- c(VAT,switch(i, private=1.12, public=1.06, 1))
    tot.price <- net.price * VAT

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

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

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

  3. 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:

> clients$type <- c('public','abroad','private','abroad')
> priceCalculator(clients$hours, client=clients$type)
[1] 1060 3960 5040 1600