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

for Loop

A for loop walks through each item in a list and does something with it, like handing a card to every student. It repeats for each element in turn.

In this page:

  1. for Loop
Syntax
r
for (item in vector_name) {
  # body using item
}

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")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using for (i in 1:length(x)) on an empty vector, where 1:0 gives c(1, 0) and the loop runs wrongly; use seq_along(x).
  2. Growing a vector inside the loop with c(result, x), which is slow for large data when vectorised code is available.
  3. Expecting the loop variable to be available in a fresh scope, when after the loop it keeps the last value.
🔒

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.