For loops

For loops are most commonly used for iterating over the elements of an object (list, vector, etc.)

for Loops in R:

 

Here is a for loop example in R.

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

x <- c("a", "b", "c", "d")
for(i in 1:4) {
print(x[i])
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
>
> x <- c("a", "b", "c", "d")
> for(i in 1:4) {
+ print(x[i])
+ }
[1] "a"
[1] "b"
[1] "c"
[1] "d"

Print out each element of ‘x’.

for(letter in x) {
print(letter)
}

Output:

[1] "a"
[1] "b"
[1] "c"
[1] "d"

For one line loops, the curly braces are not strictly necessary.

 

for(i in 1:4) print(x[i])

Output:

[1] "a"
[1] "b"
[1] "c"
[1] "d"

Nested for loops in R:

for loops can be nested inside of each other like the below example.

 

x <- matrix(1:10, 5, 2)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}

Output:

[1] 1
[1] 6
[1] 2
[1] 7
[1] 3
[1] 8
[1] 4
[1] 9
[1] 5
[1] 10

If-else condition

While loops