For Loops and While Loops - R Basics

In this article, we go over another programming fundamental called loops.

Hey everyone! It's going to be a short one today as I'm going to be talking about For Loops and While Loops. These loops are useful when you need to perform a certain action or a series of actions across multiple objects / observations.

For Loops

As the name suggests, For Loops are useful in allowing us to iterate over an object (like vectors and lists) and execute a block of code (a series of actions) for every loop we go through. Here's the syntax for a For Loop:

for (temporary_variable in object){
    # Execute some code for every loop
}

Let's look at some examples to get a better understanding.

Looping over a vector

There are different ways to loop through a vector but today I will be showing you two of them. The first way is to create a temporary variable.

vec <- c(1,2,3,4,5)

for (temp_var in vec){
    print(temp_var)
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Now to clarify, you can rename the temp_var into anything you want like 'obj' or 'i' or 'abcd' and it will still work. Just make sure you name it something that you can easily understand or refer to.

Another way of looping through a vector is giving a specific number of times for the loop to perform. The usual method for applying this is to loop based on the number of rows available in a data structure (vectors, dataframes, lists, etc.)

for (i in 1:length(vec)){
    print(vec[i])
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

In this example, I'm telling R that in 1 to 5 (number of elements in vec), which means I want it to print out the element for that index number. We can also use both of these methods for Lists and Matrices as well.

While Loops

While Loops are loops that will continue running some block of code until a certain condition is invalid. The syntax for a While Loop in R is as follows:

while (condition){
    # Code executed here while condition is true
}

A major concern when working with While Loops is that you must make sure that the condition will be invalid at some point in the future, otherwise the program will keep running forever! In case this happens, you can use Ctrl+C to kill a process in R Studio.

Before continuing on, I will be using the cat function. The cat function stands for 'Concatenate and Print' and it allows us to print statements that contain a variable. Another thing that I would like to add on is \n which is an escape character for telling R to make a new line.

Let's look at a simple example together:

x <- 0

while (x < 5){
    cat('x is currently: ',x)
    print('x is less than 5, adding one to x')
    x <- x+1
}

x is currently:  0[1] "x is less than 5, adding one to x"
x is currently:  1[1] "x is less than 5, adding one to x"
x is currently:  2[1] "x is less than 5, adding one to x"
x is currently:  3[1] "x is less than 5, adding one to x"
x is currently:  4[1] "x is less than 5, adding one to x"

while (x < 5){
    cat('x is currently: ',x,'\n')
    print('x is less than 5, adding one to x')
    x <- x+1
}

x is currently:  0 
[1] "x is less than 5, adding one to x"
x is currently:  1 
[1] "x is less than 5, adding one to x"
x is currently:  2 
[1] "x is less than 5, adding one to x"
x is currently:  3 
[1] "x is less than 5, adding one to x"
x is currently:  4 
[1] "x is less than 5, adding one to x"

By default, if you use cat and print, the output will be in a single line, which is why I added '\n' to tell R to create a new line.

break

Break is used to break out of a loop and make R skip a certain block of code.

x <- 0

while (x < 5){
    cat('x is currently: ',x,'\n')
    x <- x+1
    if (x == 5){
        print('x is equal to 5')
        print('PRINT ME OUT TOO!')
    }
}

x is currently:  0 
x is currently:  1 
x is currently:  2 
x is currently:  3 
x is currently:  4 
[1] "x is equal to 5"
[1] "PRINT ME OUT TOO!"

while (x < 5){
    cat('x is currently: ',x,'\n')
    x <- x+1
    if (x == 5){
        print('x is equal to 5')
        break
        print('PRINT ME OUT TOO!')
    }
}

x is currently:  0 
x is currently:  1 
x is currently:  2 
x is currently:  3 
x is currently:  4 
[1] "x is equal to 5"

As you can see in this example, my initial code said that once x reaches 5, print out 2 statements. Then afterwards, I added a 'break' in between, so that when x reaches 5, it will break the loop and won't print the 2nd statement. Play around with break, put it in different places within a loop and see what happens.

That's all I have for today regarding loops and see you guys next time!