R: for and while loops


I. Introduction

In computer programming, a loop is a perfect tool to use if an action or group of actions need to be repeated over and over until a certain condition is reached. Once the condition is reached, the loop stops and the instructions are no longer run again. In programming, for and while loops are extremely popular loop functions.


II for loops

for loops allow us to cycle (loop) through the elements in a vector. As the for loop cycles through each element, the primary code found within the for loop is run using each element in incremental fashion.

The following example will cycle through the code three times. The first cycle i = 1, the second cycle i = 2, and the third cycle i = 3. During each cycle, the print function will be executed. Thus, the variable i will be printed during each cycle, as shown below.

> for(i in 1:3)
+ {
+   print(i)
+ }
[1] 1
[1] 2
[1] 3

The following example will cycle through the code four times. As the code cycles through, the index variable will incrementally take on 2, 4, 6, and 8. During each cycle, the index will be squared and then printed.

> # DEFINE x
> x = c(2, 4, 6, 8)
> 
> for(index in x)
+ {
+   print(index^2)
+ }
[1] 4
[1] 16
[1] 36
[1] 64

The following code begins by creating an empty vector labeled as k, think of k as an empty hat. Then we will cycle through the body of the code 5 times. Each time, we will create a random variable, drawn from the standard normal distribution, and then store it in k

> # CREATE AN EMPTY VECTOR
> k = c()
> 
> for(j in 1:5)
+ {
+   k[j] = rnorm(1)
+ }
> 
> k
[1] -0.03199322  1.31996556  2.14375972  0.69690894 -1.32154764

III while loops

while loops are more simplistic than for loops. With while loops, the program cycles through the code repeatedly until a defined condition is met.  

> # DEFINE J
> j = 1
> 
> while(j < 5)
+ {
+   print(j)
+   
+   # INCREASE VALUE OF j by 1
+   j = j + 1
+ }
[1] 1
[1] 2
[1] 3
[1] 4
>

 

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.