Best way to iterate using for loop

2020-02-15 08:22发布

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.

标签: r loops for-loop
2条回答
叛逆
2楼-- · 2020-02-15 08:49

Just write your own helper function

loop_seq <- function(start,end) {
    if(end<start) return(integer(0))
    seq(start, end)
}

for(i in loop_seq(3,4)) {print(i)}
# [1] 3
# [1] 4
for(i in loop_seq(3,3)) {print(i)}
# [1] 3
for(i in loop_seq(3,2)) {print(i)}
# {nothing}

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.

查看更多
老娘就宠你
3楼-- · 2020-02-15 09:02

Given your example above (C++/Java) you are essentially looking at a while loop.

To replicate you example:

start = 5
end = 3
i <- start

while(i <= end){
  print(i)
  i = i+1
}

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.

查看更多
登录 后发表回答