Home > other >  How can I skip multiple for loop iterations in R like Python?
How can I skip multiple for loop iterations in R like Python?

Time:01-14

As you can see in python code below if condition is satisfied, iteration skips 1, 5, and 9.

range_iter = iter(range(10))

for i in range_iter:
    print(i)
    if i % 4 == 0:
        next(range_iter)
        print('Condition satisfied',i)


0
Condition satisfied 0
2
3
4
Condition satisfied 4
6
7
8
Condition satisfied 8

I tried this. But it was no use.

library(iterators)

range_iter <- iterators::iter(0:9)

for (i in range_iter) {
  if (i %% 4 == 0) {
    next(range_iter) 
    print(paste("Condition satisfied",i))
  }
}

I get en error:Error in i%%4 : non-numeric argument to binary operator

How can I do this in R ?

CodePudding user response:

R doesn't have any command to skip the next iteration. The next statement (alone, not a function call like next(range_iter)) will skip the current one.

So to do what you want you'd write the loop like this:

skip <- FALSE
for (i in 0:9) {
  if (skip) {
    skip <- FALSE
    next
  }
  print(i)
  if (i %% 4 == 0) {
    skip <- TRUE 
    print(paste("Condition satisfied",i))
  } 
}
#> [1] 0
#> [1] "Condition satisfied 0"
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] "Condition satisfied 4"
#> [1] 6
#> [1] 7
#> [1] 8
#> [1] "Condition satisfied 8"

Created on 2023-01-14 with reprex v2.0.2

CodePudding user response:

The modolo syntax in R is %% :

for (i in seq(0,10)) {
  if (i%%4==0) {
    print(paste("Condition satisfied",i))
  }else{
    print(i)
  }
}

[1] "Condition satisfied 0"
[1] 1
[1] 2
[1] 3
[1] "Condition satisfied 4"
[1] 5
[1] 6
[1] 7
[1] "Condition satisfied 8"
[1] 9
[1] 10

since R uses 1 based index by default, therefore

if you want 0 based you have to specify that in the iterator

  • Related