R Loops

for Loop

Basic Structure

for (condition) {
    // code block
}

Example

Iterates over the range 1 to 5 and prints each value.

for (i in 1:5) {
  print(paste("Value is", i))
}

while Loop

Basic Structure

while (condition) {
    // code block
}

Example

The loop runs as long as x <= 5 remains TRUE.

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

repeat Loop

repeat runs indefinitely unless a break condition is met.

x <- 1
repeat {
  print(x)
  x <- x + 1
  if (x > 5) {
    break
  }
}

break Statement

Loop stops completely when i == 6.

for (i in 1:10) {
  if (i == 6) {
    break
  }
  print(i)
}

next Statement

Skips the value and goes to the next iteration

for (i in 1:5) {
  if (i == 3) {
    next
  }
  print(i)
}

Skips the value 3 and continues with the next iteration.

Nested Loops

Used for matrix operations or combinations of multiple sequences.

for (i in 1:3) {
  for (j in 1:2) {
    print(paste("i =", i, ", j =", j))
  }
}

Best Practices

  • Use lapply or apply for performance over large data
  • Be cautious with infinite repeat loops — always provide a break
  • Avoid deeply nested loops by separating logic into functions

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic