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:
Syntax
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
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
cat("Fruit:", fruit, "\n")
}
for (i in seq_along(fruits)) {
cat(i, ":", fruits[i], "\n")
}
Login to try C/C++/Java/PHP code in the editor
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
- Using
for (i in 1:length(x))on an empty vector, where1:0givesc(1, 0)and the loop runs wrongly; useseq_along(x). - Growing a vector inside the loop with
c(result, x), which is slow for large data when vectorised code is available. - 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: