## The for loop

The for loop is useful for iteratively executing a group of instructions. The general format is given by


for(variation in a sequence) expression


A sequence inside the pair of braces next to for is considered. For every element in the sequence, the expression will be evaluated. The expression can be either a simple statement or a set of complex statements which may or may not involve the iterated elements. See the example below:


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


In the above code, the 1:10 creates a seqence from 1 to 10. The keyword in refers to individual elements in this sequence. The letter i is a variable name which refers to the element in the sequence. Any name can be used instead of this. The statement for(i in 1:10) iterates through every element from 1 to 10, and the command print(i) is executed 10 times for every value of i in the sequence. Consequently, the values of i from 1 to 10 are printed. After the 10 executions, the for loop terminates, resulting in the following output:


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


#### for loop through a vector by element

The for loop in R can be used in two ways. In the first way, we can access the elements of a vector directly though an iteration inside a for statement. See the example below:


avec <- c(2.1, 3.2, 4.3, 5.4, 6.5, 7.6)

for( num in avec)
{
num = num*10

print(num)
}


In the above script, a vector avec is created with 6 numbers. The statement for( num in avec) assigns the elements of avec iteratively to the variable num. Inside the loop defined by a pair of curly braces, every value of num is multiplied by 10 and printed, resulting in the following output:


[1] 21
[1] 32
[1] 43
[1] 54
[1] 65
[1] 76


#### for loop through a vector by index

In the second method, elements of a vector can be iteratively accessed inside the for loop by the index generated inside. This method is adopted in the following script:


avec <- c(2.1, 3.2, 4.3, 5.4, 6.5, 7.6)

for( i in 1:length(avec) )
{
num = avec[i]*10

print(num)
}


in the above example, length(avec) returns a number 6 which is the length of the vector as defined in the code. Thus, 1:length(avec) generates a sequence from 1 to 6. As we have seen before, the for loop iterates through this sequence assigning values 1 to 6 for the variable i . Inside the loop, avec[i]*10 accesses the values of vector avec using this index and multiplies it by 10. The resulting output is presented here:


[1] 21
[1] 32
[1] 43
[1] 54
[1] 65
[1] 76