[R] how does while work

Jim Lemon bitwrit at ozemail.com.au
Fri Mar 22 11:49:04 CET 2002

This thread is fast becoming a citation classic. I thought it would have
been resolved in a one-liner, but...

What you really want to know is how Boolean logic works in stack-based
computing. while() and for() evaluate their conditional(s) before
executing the statement(s) that they are controlling. do() evaluates
after execution. However, they all depend upon the same operator to
delimit the statement(s) that they control (in R at least). Thus, you
aren't allowed to do what jimi wants, to evaluate the while() condition
before the for() condition like this:

while (x <100) {
  for (i in 1:101) {
    i -> x
    x -> a
 } # end of while()
  } # end of for()

What has to be done is something like this:

for(i in 1:101) {
 if(x<100) a<-x

Now the conditional (x<100) takes precedence over the assignment, which
was what was intended. Before anyone accuses me of preaching, I have
made the same mistake (and worse) many times.



More information about the R-help mailing list