Loops are a basic structure in programming that take a block of code and run it repeatedly. For loops are one of the types of loops that nearly all languages contain. R’s for loops are an integral part of analyzing data.

They serve a variety of purposes, from formatting output to running calculations on large data sets. The use of for loops in R makes data analysis easier to perform.

R’s Basic for Loop

The R language’s for loop functions similarly to the standard for loops found in Go and most other programming languages. Given a starting point, it will run the code contained within it a given number of times.

A counter holds the iteration that the loop is currently on, and you can access it from the associated code block. Loops can run for a fixed number of iterations, or for the total length of an array, vector, or list.

Fixed Iteration Loops

Fixed iteration loops in R take the following form:

        for (x in 1:10) {
  print(x)
}

The x in the loop is the variable that will store the loop iteration.

After the “in” keyword are the starting and ending points of the loop. The loop will start its iterator at the first number.

After each time the code in the loop runs, it will check if the iterator is equal to the number after the colon.

If it is, code execution will continue after the loop. If it isn’t, the iterator will increase by 1, and the code block in the brackets will run again.

Output of an R program that uses a fixed iteration loop to print the numbers from 1 to 10

For Loops on Arrays, Lists, and Vectors

Just like looping through a dictionary in Python, you can iterate over appropriate data structures in R using the for loop. You can use any iterable data structure after the “in” keyword, in place of a fixed start and end point.

Looping this way will change the code’s behavior. Here, the loop will function like a foreach loop from languages like C#:

        employees <- list("Ben", "Jane", "Suzi", "Josh", "Carol")

for (x in employees) {
  print(x)
}

Now, instead of x holding the current iteration of the loop, it will hold the object from the array or list that the loop is currently on. After each loop completes, if there are more items in the list, array, or vector, x will be set to the next item. If there aren’t more items, then execution will continue with the code after the loop.

Output of an R program that loops over a list and prints its contents

The c Primitive Function and for Loops

In addition to already populated data structures, R can compose a new one in the declaration of the for loop. To do so, use the c function to combine multiple elements into a new vector.

You can simplify the example above using this method:

        for (x in c("Ben", "Jane", "Suzi", "Josh", "Carol")) {
  print(x)
}

Note that the output is just the same as before:

Output of an R program that loops over an anonymous vector to print it contents

R’s Jump Statements

Two statements let you skip loop iterations: break and next. They accomplish this in different ways. You should make sure you know the difference between the two.

The break Keyword

When a loop encounters a break statement inside itself, it immediately closes the loop. Since the program exits the loop once it hits the break keyword, it won't run any of the remaining code again:

        days <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
 "Sunday")

for (x in days) {
  if (x == "Saturday") {
    break
  }

  print(x)
}

The above loop will print out all the weekdays, but neither of the weekend days.

Output of an R program that uses the break statement to exit a loop

The next Keyword

The next keyword also skips an iteration, but unlike break, next doesn’t close the loop immediately. The loop remaining open means that any additional code within the current loop will not run, but the next iteration will continue as planned:

        days <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
 "Sunday")

for (x in days) {
  if (x == "Saturday") {
    next
  }

  print(x)
}

This loop will output each weekday and Sunday, but it won't print out Saturday.

Output of an R program that uses the next statement to skip some iterations of a loop

Example for Loops in R

There are a wide variety of situations in which for loops are useful in R. They can be a great way to run repetitive calculations, such as adding numbers to get a total:

        orders <- list(23.4, 699.8, 1042.0)
total <- 0.0

for (order in orders) {
  total <- order + total
}

cat("the total is $", total, "\n")

This example will add an order total from each individual order in a list to the overall total.

Output of an R program that uses a loop to calculate the total sum from a list

Alternatively, a for loop can help you quickly and easily output large quantities of well-formatted data:

        day_totals <- c(567.82, 364.72, 762.81, 354.99, 622.87)

for (day in 1:length(day_totals)) {
  cat("Day #", day, ": $", day_totals[day],"\n")
   day <- day + 1
}

You can use a for loop to print out each day of the week and the total sales for that particular day.

Output of an R program that uses a loop to print a series of values from a list as formatted values

You can use a for loop to calculate results and make them available to code outside the for loop, to gain a variety of information:

        test_scores <- c(67, 89, 72, 44)
score_total <- 0
num_tests <- 0

for (score in test_scores) {
  score_total <- score_total + score
  num_tests <- num_tests + 1
}

average_score <- score_total / num_tests
print(average_score)

The above loop will calculate the average score students achieved on a test.

Output of an R program that uses a for loop to calculate an average

Everything You Need to Know About R’s for Loops

Learning how to run a set number of loops or iterate over a data set without a fixed length is essential.

Whether you need to perform repeated calculations on an array, print every item in a list, or show a large batch of data in a readable form, R’s for loop can help.

Understanding the underlying principles behind for loops is a valuable skill to have in your arsenal, and mastering it can help you write simple, easy-to-read code.