jalapic
jalapic

Reputation: 14202

Extracting result from a for loop inside while loop - r

I'm not that used to writing while loops in R. Wonder if anyone could show me how to get the first result of i from this simplified version:

I've tried doing it storing the i as a vector.

Essentially, I want to know the first number from 1 to 100 for which

(z - i) / 10 is less than 9

z <- 100
p <- z/10
myi <- NULL

while(p>=9){

  for(i in 1:100){
    myi[[i]] <- i
    p <- (z-i)/10
  }
break()
}

When this breaks, p=0 and I'm not sure why. What I want to return is 11, i.e. the first instance where (z-1)/10 is not greater than or equal to 9.

If I return myi it just shows every number from 1 to 100. Thanks.

EDIT:

I'm interested in other fast approaches to this question - the following is the fastest I can work out:

which.max(sapply(seq_along(1:100), function(x) (z-x)/10 < 9))

but still would like to work out how to do this using the while loop

Upvotes: 1

Views: 606

Answers (1)

Jthorpe
Jthorpe

Reputation: 10177

There are 2 general ways of accomplishing this task with a while loop. The first is to test for the condition you want in the while loop's condition statement, as in:

#initialize i
i = 1
while((z-i)/10 < 9)# test for the condition of interest 
    # incremenet i
    i = i + 1

And the second is to use a while(TRUE) loop, and to test for the condition in the body of the while loop and break out of the loop if the condition is met, as in:

#initialize i
i = 1
while(TRUE) {
    # test for the condition of interest
    if((z-i)/10 < 9)
        # break if the condition is met
        break
    # incremenet i
    i = i + 1
}

in both of these solutions i is the first value that meets your condition. Also notice that break is used as a keyword and not a function call.

Also probably the only way to get much faster than this solution is to implement it C++ as in the accepted response to this question.

Upvotes: 3

Related Questions