[R] While loop working with TRUE/FALSE?

Feng Li m at feng.li
Wed Feb 1 17:39:35 CET 2012


I guess you want something like

w=F
z <- c(0,1,2,3,4,5,6,7,8,9)
r <- 7

    while(w == F) {
         for ( i in 1:10 ){
                 w <- r == z[i]
                 print(w)
         }
}

But this loop will run forever. The condition for "while" is checked 
when i jumps from 10 to 1. At that moment w is always FALSE.

Feng

On 02/01/2012 05:12 PM, Berend Hasselman wrote:
>
> 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
>

-- 
Feng Li
Department of Statistics
Stockholm University
106 91 Stockholm, Sweden
http://feng.li/

  * English - detected
  * Chinese
  * English
  * Swedish

  * Chinese
  * English
  * Swedish

  <javascript:void(0);> <#>



More information about the R-help mailing list