While Statements & REPEAT


Similar to a loop function, the while statement can be used to perform an operation while a given condition is true.  For example:

z <-0

while (z<5){

z<-z+2

print(z)

}

[1] 2

[1] 4

[1] 6

 

In the above while statement we initiate z to have a value of 0.  We then state that as long as z is less than 5 we will continue to perform the following loop operation z<-z+2.

Thus we have

z <- 0+2  ##Initially z is 0, but after the first iteration of the loop the value of z is 2

z <- 2+2  ## After the second iteration the value of z is 4

z <- 4+2  ## After the third iteration the value of z is 6

 

The while statement stops here because now z is now bigger than 5.

 

Another option for looping is the repeat function. An example follows:

> i<-1

> repeat{

+    print(i)

+    if( i == 15) break

+    i<-i+1

+           }

[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

[1] 6

[1] 7

[1] 8

[1] 9

[1] 10

[1] 11

[1] 12

[1] 13

[1] 14

[1] 15

 

All of these examples are analogous to MACROS in SAS. We want to do something many times, without doing it by hand each time; we are automating the process.

These methods can be greatly expanded to do dynamic, efficient, extremely complicated operations. The idea of this section is really just to get you familiar with how these programs do complicated operations.