← Back to R Course | Chapter 4: Control Flow | Lesson 3 of 6

for Loop

In this page:

  1. for Loop

for Loop

A for loop in R iterates over each element of a vector or list, executing the loop body once per element. Unlike C-style loops, R's for doesn't use an index counter by default -- it directly hands you each value. Because R favors vectorized operations, for loops are used less often than in other languages, but are still essential for certain tasks.

Note: for (i in seq_along(v)) is safer than for (i in 1:length(v)) -- the latter breaks if v has zero elements.

Example: for Loop

markup
fruits <- c("apple", "banana", "cherry")

for (fruit in fruits) {
  cat("Fruit:", fruit, "\n")
}

for (i in seq_along(fruits)) {
  cat(i, ":", fruits[i], "\n")
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.