[R] While loop working with TRUE/FALSE?

Berend Hasselman bhh at xs4all.nl
Wed Feb 1 17:12:01 CET 2012


On 01-02-2012, at 16:55, Chris82 wrote:

> Hi R users,
> 
> is there any possibilty that a while loop is working like that:
> 
> z <- c(0,1,2,3,4,5,6,7,8,9)
> r <- 7
> 
>   while(w == T) { 
>        for ( i in 1:10 ){
>                w <- r == z[i]
>                print(w)  
>        }
> }
> 
> 
> The loop should stop if w == TRUE

1. This won't work since the variable w doesn't exist at the start of the while loop.
2. The while loop condition is incorrect: it should be while( w == FALSE)
3. Don't use T and F. Use TRUE and FALSE.
4. If there is no element of z equal to r the loop will run forever (with the correct condition of course).

A much better way of doing what you seem to be wanting is

which(z == r)

or possibly

any(z == r)

Berend



More information about the R-help mailing list