R - For Loop


Advertisements


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

R’s 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

Live Demo
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"

r_loops.htm

Advertisements