Loops allow you to execute a piece of code multiple times. There are two important kinds of loops in R, for loops and while loops.

For loops

A for loop iterates a variable through all of the elements of a vector or a list. Some examples of the syntax are below:

for(i in 1:5){
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
number_words <- c("one", "two", "three", "four", "five")

for(i in number_words){
  print(i)
}
## [1] "one"
## [1] "two"
## [1] "three"
## [1] "four"
## [1] "five"

While loops

While loops continue to be executed while a specified logical expression evaluates to TRUE. The logical expression in the following example is x < 1.

x <- -4
while(x < 1){
  print(x)
  x <- x + 1
}
## [1] -4
## [1] -3
## [1] -2
## [1] -1
## [1] 0

Controlling loops

The two functions break and next manipulate the behavior of loops. The break function will immediately exit a loop, while the next function will immediately skip to the next iteration of the loop.

for(i in 8:1000000){
  print(i)
  if(i >= 10){
    break
  }
}
## [1] 8
## [1] 9
## [1] 10
for(i in 5:7){
  if(i == 6){
    next
  }
  print(i)
}
## [1] 5
## [1] 7

Home