for Loop
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: