Standard control structures. In R, for loops iterate over any vector. Prefer vectorised operations over loops where possible — but loops are fine for complex sequential operations. ifelse() is the vectorised alternative to if/else.
# if / else
x <- 15
if (x > 10) {
cat("large\n")
} else if (x > 5) {
cat("medium\n")
} else {
cat("small\n")
}
# Vectorised ifelse
scores <- c(8, 3, 6, 9, 2)
ifelse(scores >= 5, "pass", "fail")
# for loop
for (i in 1:5) {
cat("Iteration", i, "\n")
}
# Looping over a vector
species <- c("Gobio", "Cottus", "Leuciscus")
for (sp in species) {
cat("Processing:", sp, "\n")
}
# while loop
count <- 0
while (count < 3) {
count <- count + 1
cat(count, "\n")
}
# break and next
for (i in 1:10) {
if (i == 3) next # skip iteration
if (i == 7) break # exit loop
cat(i, "")
}
# ── Example using iris ──────────────────────────────────────────
# if/else on a statistic
mean_sl <- mean(iris$Sepal.Length)
if (mean_sl > 5.5) {
cat("Mean sepal length is large:", mean_sl, "
")
} else {
cat("Mean sepal length is small:", mean_sl, "
")
}
# for loop over species
for (sp in levels(iris$Species)) {
n <- sum(iris$Species == sp)
avg <- mean(iris$Sepal.Length[iris$Species == sp])
cat(sp, ": n=", n, ", mean SL=", round(avg, 2), "
")
}
# while: find first species with SL > 7
i <- 1
while (iris$Sepal.Length[i] <= 7) i <- i + 1
cat("First row with SL > 7:", i, "(", as.character(iris$Species[i]), ")
")