R For Loop

The for loop steps through each element of a sequence, such as a vector, a list, or a range of numbers, and runs its body once per element, which makes repetitive tasks over known collections concise and predictable.

The basic syntax

A for loop starts with for, followed by a loop variable and the keyword in, followed by the sequence you want to step through, all inside parentheses, then the body in curly braces. On each pass, the loop variable is set to the next value from the sequence, and the body runs using that value.

Example

for (i in 1:5) {
  print(i)
}

Looping over vectors

The sequence after in doesn't have to be a range of numbers, it can be any vector. When you loop over a character vector, the loop variable takes on each string in turn, which is handy for processing lists of names, labels, or file paths.

Looping Over a Vector

fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
  cat("I like", fruit, "\n")
}
  • A numeric range created with : or seq(), like 1:10
  • A vector of any type, such as character or logical values
  • The elements of a list, including lists that mix different types
  • The column names of a data frame, using names(df)

Looping with an index using seq_along()

Sometimes you need both the position and the value while looping. seq_along(x) generates the sequence of valid indices for x, that is 1, 2, 3, and so on up to its length, and is safer than 1:length(x). If x happens to be empty, 1:length(x) incorrectly produces 1:0, which is c(1, 0), while seq_along(x) correctly produces an empty sequence and the loop body never runs.

Looping With an Index

fruits <- c("apple", "banana", "cherry")
for (i in seq_along(fruits)) {
  cat(i, "-", fruits[i], "\n")
}
Featurefor loopwhile loop
Best suited forA known sequence or collectionA condition that changes over time
Stops whenThe sequence is exhaustedThe condition becomes FALSE
Loop variableSet automatically from the sequenceMust be updated manually in the body
Note: R is a vectorized language, so operations like toupper(fruits) or sapply() will often run faster and read more clearly than looping element by element. Reach for a for loop when the vectorized approach isn't obvious, or when each step depends on the result of the previous one.