if / else, for, while, break, next

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.

basics
# 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, "")
}