How to Create a Nested For Loop in R (Including Examples)


A nested for loop allows you to loop through elements in multiple vectors (or multiple dimensions of a matrix) and perform some operations.

The basic structure of a for loop in R is:

for(i in 1:4) {
  print (i)
}

[1] 1
[1] 2
[1] 3
[1] 4

And the basic structure of a nested for loop is:

for(i in 1:4) {
  for(j in 1:2) {
    print (i*j)
  }
}

[1] 1
[1] 2
[1] 2
[1] 4
[1] 3
[1] 6
[1] 4
[1] 8

This tutorial shows a few examples of how to create nested for loops in R.

Example 1: Nested For Loop in R

The following code shows how to use a nested for loop to fill in the values of a 4×4 matrix:

#create matrix
empty_mat <- matrix(nrow=4, ncol=4)

#view empty matrix
empty_mat
     [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]   NA   NA   NA   NA
[3,]   NA   NA   NA   NA
[4,]   NA   NA   NA   NA

#use nested for loop to fill in values of matrix
for(i in 1:4) {
  for(j in 1:4) {
    empty_mat[i, j] = (i*j)
  }
}

#view matrix
empty_mat

     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    4    6    8
[3,]    3    6    9   12
[4,]    4    8   12   16

Example 2: Nested For Loop in R

The following code shows how to use a nested for loop to square each value in a data frame:

#create empty data frame
df <- data.frame(var1=c(1, 7, 4),
                 var2=c(9, 13, 15))

#view empty data frame 
df

  var1 var2
1    1    9
2    7   13
3    4   15

#use nested for loop to square each value in the data frame
for(i in 1:nrow(df)) {
  for(j in 1:ncol(df)) {
    df[i, j] = df[i,j]^2
  }
}

#view new data frame
df

  var1 var2
1    1   81
2   49  169
3   16  225

A Note on Looping

In general, nested for loops perform fine on small datasets or matrices but they tend to be fairly slow with larger data. 

For big data, the family of apply functions tend to be much quicker and the data.table package has many built-in functions that perform efficiently on larger datasets.

Additional Resources

How to Loop Through Column Names in R
How to Append Rows to a Data Frame in R

Leave a Reply

Your email address will not be published.