For Loop In R

For loop in R is just like any other language. The basic syntax is shown below.

for (val in sequence) {

Your R statements

}

Let us go through a simple example. Let us create a sequence of even numbers in R using seq function first.

In [1]:
even_seq = seq(2,10,by=2)
In [2]:
typeof(even_seq)
'double'

Let us for loop through above sequence.

In [3]:
for (n in even_seq)
    print(n)
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10

Note we don't need curly brackets, it is optional around the for loop. Here is an example with curly brackets.

In [4]:
for (n in even_seq) {
    print(n)
}
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10

Let us expand our example, check if number is even or not.

In [5]:
for (n in even_seq) 
    if ( n%%2==0) 
        print(paste(n," is even"))
    else
        print(paste(n, "is odd"))
Error in parse(text = x, srcfile = src): <text>:4:5: unexpected 'else'
3:         print(paste(n," is even"))
4:     else
       ^
Traceback:

However the brackets around if else loop is not optional. Let us put the curly brackets around "if else" and re-run our code.

In [6]:
for (n in even_seq) 
    if ( n%%2==0) {
        print(paste(n," is even"))
    } else {
        print(paste(n, "is odd"))
    }
[1] "2  is even"
[1] "4  is even"
[1] "6  is even"
[1] "8  is even"
[1] "10  is even"

How to for loop through DataFrame in R

In [7]:
even_seq <- data.frame(even_numbers=seq(2,10,by=2))

Let us add a odd number too in our dataframe.

In [8]:
even_seq[6,] = 7
In [9]:
head(even_seq)
A data.frame: 6 × 1
even_numbers
<dbl>
1 2
2 4
3 6
4 8
510
6 7

Let us loop through dataframe same way as we did above.

In [10]:
for (n in even_seq) 
    if (n%%2==0) {
        paste(n,"is even")
    } else {
        paste(n, "is odd")
    }
Warning message in if (n%%2 == 0) {:
“the condition has length > 1 and only the first element will be used”

Oops looks like it didnt work. Let us remove the if else and just print numbers in the loop.

In [11]:
for (n in even_seq) 
    print(n)
[1]  2  4  6  8 10  7

Ok, as we see above instead of looping through each value, all the values are just printed on the same line. That is why if else loop didnt work as we expected.

In [12]:
typeof(even_seq$even_numbers)
'double'

So the correct way to loop through dataframe list of values is to use lapply function as shown below.

In [13]:
lapply(even_seq$even_numbers, function(x) {
    if (x%%2==0) {
        paste(x,"is even")
    } else {
        paste(x, "is odd")
    }
})
  1. '2 is even'
  2. '4 is even'
  3. '6 is even'
  4. '8 is even'
  5. '10 is even'
  6. '7 is odd'

Let me explain, what I did in the above code. I passed in the column 'even_number' to lapply R method. Second argument is the function that gets applied on each value. Therefore for each value in our column 'even_seq$even_numbers', function which checks whether the number is even or odd is called.

Let us make it more complex and create a data frame with two columns.

In [14]:
odd_even_seq <- data.frame(even_numbers = seq(2,10,by=2),odd_numbers=seq(1,10,by=2))
In [16]:
head(odd_even_seq,2)
A data.frame: 2 × 2
even_numbersodd_numbers
<dbl><dbl>
121
243

Ok, we have dataframe with two columns. Let us loop through the dataframe and check if it is even or odd.

In [17]:
lapply(names(odd_even_seq),  function(y) {
    lapply(odd_even_seq[[y]],function(x) {
          if (x%%2==0) {
                paste(x,"is even")
        } else {
                paste(x, "is odd")
        }
    })
    
})
    1. '2 is even'
    2. '4 is even'
    3. '6 is even'
    4. '8 is even'
    5. '10 is even'
    1. '1 is odd'
    2. '3 is odd'
    3. '5 is odd'
    4. '7 is odd'
    5. '9 is odd'

Note to make it work, we used two lapply functions. First one is to loop through the list of column names and then 2nd one is to loop through the list of values of each column.

Wrap Up!

I hope you would find this tutorial useful.