SyntaxStudy
Sign Up
R Loops: for, while, and repeat
R Beginner 2 min read

Loops: for, while, and repeat

R supports three loop constructs. The for loop iterates over each element of a vector or list: for (variable in collection) { body }. The loop variable takes each value in turn and the body is executed once per value. Although explicit loops are often replaced by vectorised operations or the apply family in idiomatic R, they remain indispensable for sequential algorithms, accumulating results across iterations, and situations where each iteration depends on the result of the previous one. The while loop repeats its body as long as a condition evaluates to TRUE. It is suitable when the number of iterations is not known in advance. The repeat loop runs indefinitely and must be exited with an explicit break statement; it is the R equivalent of a do-while loop and is useful when you need to execute the body at least once before checking the exit condition. Two control flow keywords modify loop behaviour: next is equivalent to continue in other languages — it skips the remainder of the current iteration and jumps to the next. break exits the innermost loop immediately. Both can be used inside for, while, and repeat loops. Pre-allocating result containers before a loop (using vector() or a numeric/character vector of the correct length) is important for performance; growing a vector inside a loop by appending forces repeated memory allocation.
Example
# for loop — iterate over a vector
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
    cat("I like", fruit, "\n")
}

# for loop with index
n <- 5
result <- numeric(n)      # pre-allocate for performance
for (i in seq_len(n)) {
    result[i] <- i ^ 2
}
result   # 1 4 9 16 25

# Nested for loop
mat <- matrix(0, nrow = 3, ncol = 3)
for (i in 1:3) {
    for (j in 1:3) {
        mat[i, j] <- i * j
    }
}
mat   # multiplication table

# next — skip even numbers
for (i in 1:10) {
    if (i %% 2 == 0) next
    cat(i, "")
}
cat("\n")   # 1 3 5 7 9

# break — exit early
for (i in 1:100) {
    if (i > 5) break
    cat(i, "")
}
cat("\n")   # 1 2 3 4 5

# while loop
count <- 1
while (count <= 5) {
    cat("count =", count, "\n")
    count <- count + 1
}

# repeat loop (must contain break)
x <- 1
repeat {
    cat(x, "")
    x <- x + 1
    if (x > 5) break
}
cat("\n")   # 1 2 3 4 5