Kirk Ammerman
Kirk Ammerman

Reputation: 19

Can you skip a count in a for loop without an if statement

Is there code that can let me skip numbers/counts in a for loop.

for (i in 2:100){ 
    argument
}

but I want to skip every ten .. so check 1-9 skip 10 and go to 11 ... skip 20 .. go to 21 .. skip another number 47 (there is no pattern to the skipped numbers in the count)etc?

Upvotes: 1

Views: 199

Answers (3)

GKi
GKi

Reputation: 39717

You can subset those to exclude.

For the loop counts:

for (i in (2:100)[-c(10,20,47)]) {
  #argument
}

or for i as you start at 2.

for (i in (2:100)[-c(10,20,47)+1]) {
  #argument
}

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

Maybe you can try something like below, which excludes 10,20 and 47 from 2:100

for (i in (v <- 2:100)[!v %in% c(10,20,47)]){ 
    argument
}

Upvotes: 1

s_baldur
s_baldur

Reputation: 33603

next

for (i in 2:10){ 
  if (i %in% c(4) || i %% 5 == 0) next
  cat(i)
}

In the above example you skip 4 and numbers divisible by 5.

Upvotes: 0

Related Questions