Loops

The purpose of a loop is to automate repetitive tasks and remove redundant code. If a piece of code is executed more than once, then it might be easier to use a for() or while() loop. The code inside a for() loop will always be executed a certain number of times, whereas a while() loop will execute code until some condition is met.

for() Loops

for() loops have three components:

  • The iterator, which is a simple variable, frequently i, that serves as a counter
  • The range, which can either be a simple range (1:10) or a vector (mtcars$mpg)
    • If you give a simple numeric range, your iterator will increase by one after every iteration
    • If you provide a vector, the loop will iterate over every element in that vector
  • The code to be executed
for(i in a:b) {
# i is the iterator
# a:b is the range
# the code to be executed goes in between the curly brackets
}

As you can see, the structure is simple. The code inside the curly brackets will be run on each iteration, so if a = 1 and b = 10, then the code will be run 10 times.

Note: In other programming languages like Python, loops and indices can start at zero, however, R does not allow this. It requires them to start with a positive index greater than zero (the default is 1). For example, if you start a loop with for(seq(1, 3, .5)) {#code}, then your loop will run from 1 to 3, and trigger at every iteration of .5: 1, 1.5, etc.

To see this in action, let’s make a running total of values from 1 through 10.

sum = 0
for(i in 1:10) {
  sum = sum + i
  print(sum)
}
## [1] 1
## [1] 3
## [1] 6
## [1] 10
## [1] 15
## [1] 21
## [1] 28
## [1] 36
## [1] 45
## [1] 55

sumvariable begins with a value of zero, and will increase to a total of 55 (the sum of integers 1 through 10).

For the following example, we will use the mtcars dataset. This is one of many datasets that are part of the datasets package in R, a package which is automatically loaded when you open R. Searching for mtcars in RStudio's Help search box provides more details on this particular dataset.

Suppose you want to print the weight of all the cars in the matcars dataset as a running total. You could just use cumsum(mtcars$wt), but you want to challenge yourself and display the car names too. Using a for() loop, you could use the following method:

numrow = nrow(mtcars)
total = 0
for(i in 1:numrow) {
row = mtcars$wt[i]
total = total + row
cat(row.names(mtcars)[i], total, '\n')
}
## Mazda RX4            2.62 
## Mazda RX4 Wag        5.495 
## Datsun 710           7.815 
## Hornet 4 Drive       11.03 
## Hornet Sportabout    14.47 
## Valiant              17.93 
## Duster 360           21.5 
## Merc 240D            24.69 
## Merc 230             27.84 
## Merc 280             31.28 
## Merc 280C            34.72 
## Merc 450SE           38.79 
## Merc 450SL           42.52 
## Merc 450SLC          46.3 
## Cadillac Fleetwood   51.55 
## Lincoln Continental  56.974 
## Chrysler Imperial    62.319 
## Fiat 128             64.519 
## Honda Civic          66.134 
## Toyota Corolla       67.969 
## Toyota Corona        70.434 
## Dodge Challenger     73.954 
## AMC Javelin          77.389 
## Camaro Z28           81.229 
## Pontiac Firebird     85.074 
## Fiat X1-9            87.009 
## Porsche 914-2        89.149 
## Lotus Europa         90.662 
## Ford Pantera L       93.832 
## Ferrari Dino         96.602 
## Maserati Bora        100.172 
## Volvo 142E           102.95

while() Loops

while() loop is used to run a chunk of code over and over until the logical value changes from TRUE to FALSE. It can be thought of as a combination of a for()loop and an if()function. The syntax is shown below:

while(a == b) {
# the code in parenthesis is some sort of TRUE/FALSE statement, called a "logical test"
# it can use any logical operator in R: >, <=, |, etc. (INCLUDE LINK TO LOGICAL OPERATORS IN WEBSITE)
# the code in between the curly brackets is executed every time the test is TRUE
}

As you can see, it is similar to an if statement. If the first test is TRUE, the code will run, and it will continue running until the condition comes back as FALSE.

Note: Unlike for() loops, while() loops have no automatic start and stop. Because of this, you must make sure to include some sort of change in your code that will eventually make the logical test become FALSE, or your loop will never end. If you ever do this, be aware that there is an option in RStudio to stop the current execution of code. You can stop code from running by locating the "stop sign" icon that appears at the top of RStudio's Console window.

To continue our example from before, suppose you want to accomplish the same task with a while() loop. You will need a counter and a variable to save the total weight of the cars, just as before. However, you will need to structure your loop slightly differently because there is no definite start or stop built into the loop.

numrow = nrow(mtcars)
total = 0
i = 1
while(i <= numrow) {
row = mtcars$wt[i]
total = total + row
cat(row.names(mtcars)[i], total, '\n')
i = i + 1
}
## Mazda RX4            2.62 
## Mazda RX4 Wag        5.495 
## Datsun 710           7.815 
## Hornet 4 Drive       11.03 
## Hornet Sportabout    14.47 
## Valiant              17.93 
## Duster 360           21.5 
## Merc 240D            24.69 
## Merc 230             27.84 
## Merc 280             31.28 
## Merc 280C            34.72 
## Merc 450SE           38.79 
## Merc 450SL           42.52 
## Merc 450SLC          46.3 
## Cadillac Fleetwood   51.55 
## Lincoln Continental  56.974 
## Chrysler Imperial    62.319 
## Fiat 128             64.519 
## Honda Civic          66.134 
## Toyota Corolla       67.969 
## Toyota Corona        70.434 
## Dodge Challenger     73.954 
## AMC Javelin          77.389 
## Camaro Z28           81.229 
## Pontiac Firebird     85.074 
## Fiat X1-9            87.009 
## Porsche 914-2        89.149 
## Lotus Europa         90.662 
## Ford Pantera L       93.832 
## Ferrari Dino         96.602 
## Maserati Bora        100.172 
## Volvo 142E           102.95

As you can see, it takes a little bit longer to do this type of thing with a while() loop; however, while() loops are well suited to finding certain information, like when a cumulative value crosses a certain threshold. See if you can find when the total weight of the cars first exceeds 50 tons.

Ready to take your skills to the next level?

Proceed to the advanced tutorials.