Conditions and loops

if / else, vectorized ifelse(), switch(), for over a vector, while, and next / break.

Runs in Zerethon IDE · R 4.5 Official R documentation ↗
main.R
for (n in 1:5) {
  if (n %% 2 == 0) {
    cat(n, "even\n")
  } else if (n == 5) {
    cat(n, "last\n")
  } else {
    cat(n, "odd\n")
  }
}

i <- 3
while (i > 0) {
  i <- i - 1
  if (i == 1) next
  cat(sprintf("i = %d\n", i))
}

fruits <- c("apple", "pear")
for (index in seq_along(fruits)) {
  cat(sprintf("%d %s\n", index, fruits[index]))
}

x <- c(5, -2, 0)
print(ifelse(x > 0, "positive", "not positive"))
print(switch("png", png = , jpg = "image", txt = "text", "other"))

Output

1 odd
2 even
3 odd
4 even
5 last
i = 2
i = 0
1 apple
2 pear
[1] "positive"     "not positive" "not positive"
[1] "image"
  • if needs a single TRUE or FALSE. For a whole vector use ifelse(), or any() / all().
  • Use && and || in if; & and | work element by element on vectors.
  • seq_along(x) is safer than 1:length(x), which gives 1 0 for an empty vector.
  • next skips to the next round of a loop and break leaves it.

Related topics

Official references