# How nested for loop work in R? Explain with an example.

796    Asked by LiamSMITH in Data Science , Asked on Dec 10, 2019

Nested for loop means We can nest for loops inside one another,but we need to be careful as every additional for loop nested inside another may cause a significant amount of additional time for our code to finish executing.

Let us create a nested loop for a matrix of 5x5

mat <- matrix(1:25,nrow=5)

for (row in 1:nrow(mat)){

for (col in 1:ncol(mat)){

print(paste('The element at row:',row,'and col:',col,'is',mat[row,col]))

}

}

Output:

[1] "The element at row: 1 and col: 1 is 1"

[1] "The element at row: 1 and col: 2 is 6"

[1] "The element at row: 1 and col: 3 is 11"

[1] "The element at row: 1 and col: 4 is 16"

[1] "The element at row: 1 and col: 5 is 21"

[1] "The element at row: 2 and col: 1 is 2"

[1] "The element at row: 2 and col: 2 is 7"

[1] "The element at row: 2 and col: 3 is 12"

[1] "The element at row: 2 and col: 4 is 17"

[1] "The element at row: 2 and col: 5 is 22"

[1] "The element at row: 3 and col: 1 is 3"

[1] "The element at row: 3 and col: 2 is 8"

[1] "The element at row: 3 and col: 3 is 13"

[1] "The element at row: 3 and col: 4 is 18"

[1] "The element at row: 3 and col: 5 is 23"

[1] "The element at row: 4 and col: 1 is 4"

[1] "The element at row: 4 and col: 2 is 9"

[1] "The element at row: 4 and col: 3 is 14"

[1] "The element at row: 4 and col: 4 is 19"

[1] "The element at row: 4 and col: 5 is 24"

[1] "The element at row: 5 and col: 1 is 5"

[1] "The element at row: 5 and col: 2 is 10"

[1] "The element at row: 5 and col: 3 is 15"

[1] "The element at row: 5 and col: 4 is 20"

[1] "The element at row: 5 and col: 5 is 25"