I'm looking for the best way to iterate in R
. I know simple solutions like:
times <- 3
for(i in 1:times){
}
BUT if times <- 0, then my loop iterates twice, not zero. So the solution is:
for(i in seq_len(times))
So if I want to iterate from start
to end
:
for(i in seq_len(end - start))
BUT if end-start < 0
then:
seq_len(-1)
Error in seq_len(-1) : argument must be coercible to non-negative integer
I know that I can check if end-start < 0
before loop, but this is not very clean solution... any other ideas?
To clarify - I'm looking for solution similar to other programming languages, like C++/Java:
for(int i = start; i < end; i++)
So if start=5
and end=3
the loop doesn't even start.
Just write your own helper function
The for loop will always iterate over a vector, so the problem really isn't the for loop, it's creating the right vector of indexes (
:
,seq_len
,seq_along
) that you need to worry about.Given your example above (C++/Java) you are essentially looking at a
while
loop.To replicate you example:
This loop will not start. Note the
<=
given that R is base-1 indexed. Of course you could just modify the indices but this is cleaner.