Non-unity incremental counter in a loop

No votes yet

On the R-help list, it was asked:

"Suppose I want to iterate something from 1 to 100, using a step size of
(say) 5. Trying the obvious

for(x in 1:5:100) {
    print(x)
}

(Perhaps obviously, I've borrowed the MATLAB convention to some degree).

Or, looping from 0 -> 1 by 0.01?"

The solution is quite simple once a person knows a bit about R. First of all, for loops are defined in what other languages call a foreach notation. The inquirer almost had it correct - without the added step size, the basic for loop would be:

for(x in 1:100) {
     print(x)
}

That is, x takes every value in the vector 1:100. To accomplish the step size component of the question, we use the seq(a,b,c) function, which creates a vector from a to b increment by c.

The solution is thus:

for(x in seq(1,100,5)) {
     print(x)
}

or, for the inquirer's second question:

for(x in seq(0,1,0.01)) {
     print(x)
}