Skip to content
Loops (and Why You Rarely Need Them)
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

R has standard loops, but idiomatic R avoids them. Vectorized operations and apply-family functions are faster and clearer.

for loop:

for (i in 1:5) {
    cat(i, "\n")
}

while:

n <- 1
while (n < 100) {
    n <- n * 2
}

But consider this — instead of:

result <- numeric(10)
for (i in 1:10) result[i] <- i * i

Write:

result <- (1:10)^2   # vectorized — faster, clearer

The sapply function applies a function to each element and simplifies the result:

sapply(1:5, function(x) x^2)   # 1 4 9 16 25

Use loops when there's genuine sequential state (Newton's method, simulations). Use vectorization for everything else.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…