1.14 Iteration using a for loop

Sometimes you want to carry out the same procedure multiple times. This is called iteration and the simplest form of iteration is the for loop. The following loop prints the elements of x, one at a time.

x <- c("A", "B", "C")

for(i in 1:length(x)) {
  print(x[i])
}
## [1] "A"
## [1] "B"
## [1] "C"

The syntax is that you define an index (in this case, the letter i) and starting (1) and stopping (length(x)) values. R sets the index to the first value, then runs the code between the { } brackets. Then it iterates, moving to the next value of the index, and re-running the code. This example also demonstrates the use of the length() function, which returns the number of elements in an object.

Here is a similar loop but with a more complicated piece of code inside. At each iteration, the paste() function combines text from the ith element of x and the the ith element y into a sentence.

x <- c("A", "B", "C")
y <- c(10, 18, 7)

for(i in 1:length(x)) {
  print(paste("Item", x[i], "weighs", y[i], "lbs.", sep = " "))
}
## [1] "Item A weighs 10 lbs."
## [1] "Item B weighs 18 lbs."
## [1] "Item C weighs 7 lbs."

For further study, see RStudio Cloud’s primer on iteration.