HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RVariablesData TypesOperatorsCharacters (character)VectorsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ Character
📚 Vector
🔀 Condition & Loop
🧩 Function
R›Loops (for / while)

Loops (for / while)

Iterating over ranges (1:5) and vectors with for, conditional repetition with while.

Simple enough for a 5-year-old to understand

range with for

The 1:5 range ALSO includes 5.

Example code
1
for (i in 1:3) {
1, 2, 3 (3 included).
Loop1, 2, 3 (3 included).
2
cat(i, "\n", sep="")
3
}
Loop
💡 Hint: 1:5 → 5 is included.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

Loops in R are written with for, while, and repeat. However, loops in R are not as central a tool as in other languages: the same task is often done shorter and faster by a vectorized operation or a function from the apply family.

Still, there are situations where a loop is needed: calculations where each step depends on the previous one, side-effect tasks like file reading, and simulations. Writing a loop in these cases is not wrong.

There are two most common mistakes when writing loops in R: generating the index range incorrectly and appending the result in each step to a vector that grows. Both have well-known and simple solutions.

What you will learn

  • writing for loops
  • generating safe indices
  • using while and repeat
  • the break and next commands
  • accumulating results efficiently

Who is this for?

  • R users learning how to write loops
  • Those who get errors when working with empty vectors
  • Those complaining about their code being slow

When to use?

Loops are inevitable in calculations where each step depends on the result of the previous one.

If an independent operation is applied to each element, a vectorized operation or the apply family should be preferred over a loop.

Common mistakes

Wrong

v <- c()
for (i in 1:length(v)) {
  print(v[i])
}

When the vector is empty, the length is zero and the colon operator counts backward between 1 and 0, producing a two-step sequence. The loop runs twice even though it should not run on an empty vector and prints NA. This is one of R's most well-known traps.

Correct

v <- c()
for (i in seq_along(v)) {
  print(v[i])
}

Wrong

sonuc <- c()
for (i in 1:1000) {
  sonuc <- c(sonuc, i * 2)
}

Because the vector is recreated at every step, the number of operations increases with the square of the number of steps; the difference becomes noticeable in thousands of steps. The correct approach is to pre-allocate the result to the correct size from the beginning and write to positions.

Correct

sonuc <- numeric(1000)
for (i in 1:1000) {
  sonuc[i] <- i * 2
}

Wrong

i <- 1
while (i <= 5) {
  print(i)
}

Since the counter never increases, the condition remains true forever and the script never ends. You have to ensure progress in while loops; therefore, for should be preferred if the number of elements is known.

Correct

i <- 1
while (i <= 5) {
  print(i)
  i <- i + 1
}

Frequently asked questions

Why is seq_along safer?

Because when the vector is empty, it produces zero steps, whereas the colon operator counts backward. seq_along always gives valid indices and in case of empty input, the loop doesn't run at all — which is the expected behavior.

Is the apply family faster than loops?

Not always noticeably, but it shortens the code and clarifies the intent. The real speed difference emerges when you avoid growing vectors inside loops. The fastest way is to remove the loop entirely and use vectorized operations.

What is the difference between break and next?

break terminates the loop completely; next only skips that step and moves to the next one. The equivalent of the continue command from other languages in R is next, though the name difference can be confusing at first.

Summary

seq_along should be used to generate indices.

The colon operator counts backward on an empty vector.

Growing a vector inside a loop is slow.

You must ensure progress in a while loop.

next is used to skip, and break is used to exit.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code