# ============================================================
# Loops in R
# R Foundations — Rverse Analytics
# https://rverseanalytics.com/learn/loops
# ============================================================

# Loops in R - repeat with for and while
# 1. A for loop runs once per element
for (i in 1:4) print(i * 10)
# 2. Loop over any vector
words <- c("alpha", "beta", "gamma")
for (w in words) print(toupper(w))
# 3. Collect results in a vector
res <- numeric(5)
for (i in 1:5) res[i] <- i^2
res
# 4. while repeats until the condition fails
n <- 1
while (n < 100) n <- n * 2
n
# 5. Often you do not need a loop at all
(1:5)^2
sum(1:100)
