R For Loop

The for statement in R is a bit different from what you usually use in other programming languages.

Rather than iterating over a numeric progression, R’s for statement iterates over the items of a vector or a list.

The items are iterated in the order that they appear in the vector.

Syntax

Here’s the syntax of the for statement:

r for loop syntax

vector is a collection of objects that can be iterated over

statement(s) are executed once for each item in a vector

var takes items from a vector one by one

Basic Examples

Example: Iterate through a vector

> colors <- c("red","green","blue","yellow")
> for (x in colors) {
+   print(x)
+ }
[1] "red"
[1] "green"
[1] "blue"
[1] "yellow"

Example: Iterate through a list

> l <- list(3.14, "Hi", c(1,2,3))
> for (x in l) {
+   print(x)
+ }
[1] 3.14
[1] "Hi"
[1] 1 2 3

If you need to execute a group of statements for a specified number of times, use sequence operator : or built-in function seq()

Example: Print ‘Hello!’ 3 times

> for (x in 1:3) {
+   print("Hello!")
+ }
[1] "Hello!"
[1] "Hello!"
[1] "Hello!"

Example: Iterate a sequence and square each element

> for (x in seq(from=2,to=8,by=2)) {
+   print(x^2)
+ }
[1] 4
[1] 16
[1] 36
[1] 64

for Loop Without Curly Braces

If you have only one statement to execute, you can skip curly braces.

Example: Print the numbers 0 to 4

> for (x in 0:4) print(x)
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4

Nested for loop

A nested for loop is a loop within a loop.

They are useful for when you want to repeat something several times for several things.

Example:

> for(x in 1:3) {
+   for(y in 1:2) {
+     print(paste(x, y))
+   }
+ }
[1] "1 1"
[1] "1 2"
[1] "2 1"
[1] "2 2"
[1] "3 1"
[1] "3 2"

Break in for Loop

In R, break statement is used to exit the loop immediately.

It simply jumps out of the loop altogether, and the program continues after the loop.

Example: Break the loop at ‘blue’

> colors <- c("red","green","blue","yellow")
> for (x in colors) {
+   if (x == "blue")
+     break
+   print(x)
+ }
[1] "red"
[1] "green"

Next (continue) in for Loop

The next statement skips the current iteration of a loop and continues with the next iteration.

Example: Skip ‘blue’ using continue statement

> colors <- c("red","green","blue","yellow")
> for (x in colors) {
+   if (x == "blue")
+     next
+   print(x)
+ }
[1] "red"
[1] "green"
[1] "yellow"