Maximilian
Maximilian

Reputation: 4229

How to set two regimes for Sys.sleep in a loop

I would like to have 2 sets of Sys.sleep. One long one and very short at each iteration. The current example does the first "long sleep" however doesn't proceed with the next one.

Here is example:

out <- as.numeric()

for(i in 1:20){
 out[i] <- i*5
  if(i==seq(5,20,5)){
   Sys.sleep(5); print("Long sleep")
  } else {
    for(j in 1:5){
     Sys.sleep(0.15); cat(j)
 }}}

out

The loop should have a "Long sleep" with 5sec at each 5th iteration and 0.15sec at each iteration.

What I'm doing wrong here? Thanks.

Upvotes: 0

Views: 230

Answers (1)

r2evans
r2evans

Reputation: 161007

The error the condition has length > 1 and only the first element will be used should have been an indicator that your if test was incorrect. Let's try it on the console:

i <- 5
i == seq(5,20,5)
## [1]  TRUE FALSE FALSE FALSE

When you do that in an if statement, it is expecting one and only one logical out of the comparison, so it is rightfully confused. (Which would you use?)

Perhaps you meant i %in% seq(5,20,5)? Even better, I suggest you pre-assign the sequence and compare against it, otherwise you are creating a static vector every time.

myseq <- seq(5,20,5)
for(i in 1:20) {
    out[i] <- i*5
    if(i %in% myseq) {
        Sys.sleep(5); print("Long sleep")
    } else {
        for(j in 1:5) {
            Sys.sleep(0.15); cat(j)
        }
    }
}

As an alternative, you could also check (i %% 5 == 0), which can be faster, depending on the size of your test sequence.

Upvotes: 5

Related Questions