The key point here is to realize that all for
in R
is executed from an array of indexes. See the example below:
for (j in 1:5){
print(j^2)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
To do this loop, I implicitly created an array of indexes with the command 1:5
:
1:5
[1] 1 2 3 4 5
In particular, this vector starts at 1 and ends at 5 with an increment of 1. If I had explicitly done to create my for
, I would get the same result:
indices <- c(1, 2, 3, 4, 5)
for (j in indices){
print(j^2)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Therefore, for
in R
is defined over the positions of a vector. This vector may be as I see fit. Let us suppose that I wish to square not the first five positive integers, but the first five prime numbers. So I would have
indices <- c(2, 3, 5, 7, 11)
for (j in indices){
print(j^2)
}
[1] 4
[1] 9
[1] 25
[1] 49
[1] 121
Notice how logic is the same? I just need to set my index vector correctly and make my counter vary in it. In your case, it would be something like
indices <- c(1, 2, 4, 5, 6, 7, 8)
for (j in indices){
# comandos a serem executados
}
Of course the indices
vector could have been defined in a less explicit way. For example, the
indices <- (1:8)[-3]
[1] 1 2 4 5 6 7 8
creates a vector with the first eight positive integers and removes the observation present in the third position.
Finally, there are several ways to solve the problem. The only feature that does not change is that R
will always make the loop counter vary in the positions of a vector, from first to last.