While loops

While loops begin by testing a condition. If it is true, then they execute the loop body. Once the loop body is executed, the condition is tested again, and so forth, until the condition is false, after which the loop exits.

Syntax of while loop:

while (condition)
{
R Code
}

Example:

 

count <- 0
while(count < 10) {
print(count)
count <- count + 1
}

Output:

[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9

Another Example:

 

z <- 8
set.seed(1) #set.seed() is used for reproducible results.

while(z >= 6 && z <= 10){
coin <- rbinom(1, 1, 0.5)

if(coin == 1) {
print("It is head")
z <- z + 1
} else {
print("It is tail")
z <- z - 1
}
}

Output:

[1] "It is tail"
[1] "It is tail"
[1] "It is head"
[1] "It is head"
[1] "It is tail"
[1] "It is head"
[1] "It is head"
[1] "It is head"
[1] "It is head"

For loops

Repeat, Next, Break