for (condition) {
// code block
}Iterates over the range 1 to 5 and prints each value.
for (i in 1:5) {
print(paste("Value is", i))
}while (condition) {
// code block
}The loop runs as long as x <= 5 remains TRUE.
x <- 1
while (x <= 5) {
print(x)
x <- x + 1
}repeat runs indefinitely unless a break condition is met.
x <- 1
repeat {
print(x)
x <- x + 1
if (x > 5) {
break
}
}Loop stops completely when i == 6.
for (i in 1:10) {
if (i == 6) {
break
}
print(i)
}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.
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))
}
}lapply or apply for performance over large datarepeat loops — always provide a breakAsk the AI if you need help understanding or want to dive deeper in any topic