R - for Loop



A For loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax

The basic syntax for creating a for loop statement in R is −

for (value in vector) {
   statements
}

Flow Diagram

R for loop

Rs for loops are particularly flexible in that they are not limited to integers, or even numbers in the input. We can pass character vectors, logical vectors, lists or expressions.

Example

v <- LETTERS[1:4]
for ( i in v) {
   print(i)
}

When the above code is compiled and executed, it produces the following result −

[1] "A"
[1] "B"
[1] "C"
[1] "D"

Example - Iterating elements of a List

list1 <- list(a = 1:3, b = "hello", c = TRUE)
for (item in list1) {
   print(item)
}

When the above code is compiled and executed, it produces the following result −

[1] 1 2 3
[1] "hello"
[1] TRUE

Example - Printing a sequence of 5 numbers

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

When the above code is compiled and executed, it produces the following result −

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
r_loops.htm
Advertisements