The key point here is to realize that for
in the R
is executed from an index vector. See example below:
for (j in 1:5){
print(j^2)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
To make this loop, I implicitly created an index vector 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 increment of 1. If I had made it explicitly before 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, the for
in the R
is set on top of the positions of a vector. This vector can be whatever I want. Let’s assume 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 the logic is the same? I just need to correctly define my index vector 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 vector indices
could have been defined in a less explicit way. For example, the command
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 from the third position.
Anyway, there are several ways to solve the problem. The only feature that doesn’t change is that the R
will always make the loop counter vary in the positions of a vector, from the first to the last.