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"
ifneeds a singleTRUEorFALSE. For a whole vector useifelse(), orany()/all().- Use
&&and||inif;&and|work element by element on vectors. seq_along(x)is safer than1:length(x), which gives1 0for an empty vector.nextskips to the next round of a loop andbreakleaves it.