ZetCode

R control flow

last modified November 19, 2026

Control flow decides which statements run and how often. R has the familiar conditional and loop constructs, plus a vectorised conditional that works on whole vectors. This article covers if and else, ifelse, the for, while, and repeat loops, the break and next statements, and the switch function.

if and else

An if statement evaluates a condition, which is an expression that produces a single value R interprets as logical, and runs the following block only when the value is TRUE. A block is a group of statements inside braces. The optional else block runs when the condition is false, and else if chains several tests in order.

if-else.R
score <- 85
if (score >= 90) {
  grade <- "A"
} else if (score >= 80) {
  grade <- "B"
} else {
  grade <- "C"
}
cat("grade:", grade, "\n")

The tests are tried from top to bottom, and the first true condition wins, so the order matters: a score of 95 matches the first branch and never reaches the second. The else must be written on the same line as the closing brace when the script is run non-interactively, because a line that ends after } is treated as a complete statement and the following else is then a syntax error.

$ Rscript if-else.R
grade: B 

Conditions must be scalar

The condition of an if must have length one. A comparison of a vector with a number produces a vector of logical values, and R refuses to guess which element should decide the branch; the error message says that the condition has length greater than one. A missing value is also rejected, because NA is neither true nor false, and the interpreter reports that a TRUE or FALSE is needed.

When the decision applies to every element of a vector, use the vectorised ifelse function or a logical index instead of if. The all and any functions reduce a logical vector to one value: all(x > 0) asks whether every element is positive, and any(x > 0) asks whether at least one is. Both accept na.rm = TRUE to ignore missing values.

ifelse

ifelse takes a logical vector, a value for the true positions, and a value for the false positions. It returns a vector of the same length as the test, which makes it the natural choice for a column of data. Keep the value arguments free of side effects, because whether and how often they are evaluated depends on the test.

vectorised-if.R
scores <- c(72, 85, 60, 90)
result <- ifelse(scores >= 70, "pass", "fail")
print(result)
print(ifelse(c(1, NA, 3) > 1, "big", "small"))

The first result has one label per score. The second shows that a missing test produces a missing result: the middle element is neither big nor small because the comparison itself is unknown. The two branches must be compatible types, since the result is one vector and therefore has one type; mixing a number and a string would turn every element into a string.

$ Rscript vectorised-if.R
[1] "pass" "pass" "fail" "pass"
[1] "small" NA      "big"  

for loops

A for loop runs its body once for each element of a sequence. The loop variable takes the value of the current element, and the body can use it by name. R has no loop counter to declare: 1:5 is an ordinary vector, and the loop walks over its elements in order.

for-loop.R
for (i in 1:5) {
  cat("i =", i, "\n")
}
cat("after the loop, i =", i, "\n")

The loop variable is an ordinary object in the current environment, so it is still visible after the loop ends and holds the last value it received. This is different from languages that scope the counter to the loop. A loop over the values of a vector is written as for (score in scores), without an index, when the position is not needed.

$ Rscript for-loop.R
i = 1 
i = 2 
i = 3 
i = 4 
i = 5 
after the loop, i = 5 

while loops

A while loop repeats its body as long as the condition stays true. The condition is tested before every iteration, so the body may run zero times when the condition is false at the start. Something inside the body must move the loop toward termination, or the program runs forever.

while-loop.R
n <- 1
while (n <= 5) {
  cat("n =", n, "\n")
  n <- n + 1
}

The variable n starts at one, and the last statement of the body increases it by one on every pass. Without that line the condition would remain true and the loop would never stop. An iteration is one pass through the body; this loop performs five of them and stops when n <= 5 becomes false.

$ Rscript while-loop.R
n = 1 
n = 2 
n = 3 
n = 4 
n = 5 

repeat and break

A repeat loop has no condition in its header and runs until a break statement executes inside the body. This form is useful when the test belongs at the end of the body, because the body must run at least once, or when the exit condition is easier to express in the middle. The break statement leaves the innermost loop immediately.

repeat-break.R
n <- 1
repeat {
  if (n > 5) break
  cat("n =", n, "\n")
  n <- n + 1
}

The check comes first, so this version behaves like the while loop. Moving the check to the end would make a do-while loop, which always prints at least one line. break also works inside for and while loops, and a loop nested inside another loop breaks only from the inner one.

$ Rscript repeat-break.R
n = 1 
n = 2 
n = 3 
n = 4 
n = 5 

next

The next statement skips the rest of the current iteration and moves to the next one, without leaving the loop. It is the R spelling of the continue statement found in other languages. The condition around it usually tests something that should be excluded from the body.

skip-next.R
for (i in 1:10) {
  if (i %% 2 == 0) next
  cat(i, "")
}
cat("\n")

Even numbers satisfy i %% 2 == 0, so the loop skips them and only the odd numbers reach cat. The final cat is outside the loop and supplies the newline that the loop itself never prints. Without that newline, the shell prompt would continue on the same line as the last number.

$ Rscript skip-next.R
1 3 5 7 9 

switch

switch chooses one of several alternatives. Its first argument is a string or a number, and the remaining arguments are the alternatives. With a string, the alternative is selected by matching the name; with a number, it is selected by position. For a string switch, an unnamed last argument serves as the default when nothing matches.

switch-cases.R
day <- "Wed"
print(switch(day,
  Mon = "Monday",
  Tue = "Tuesday",
  Wed = "Wednesday",
  "unknown"))
print(switch(2, "one", "two", "three"))

The first call matches the name Wed and returns its value. The second call uses position two, so it returns "two". A named switch with no match returns the default; without a default it returns NULL, which prints as NULL and disappears when used in a longer expression. The alternatives do not have to be strings; any expression is allowed.

$ Rscript switch-cases.R
[1] "Wednesday"
[1] "two"

Vectorised alternatives

A loop is not needed when the operation applies to every element independently. R's operators and functions already work on whole vectors, and sum, mean, any, and all reduce a logical vector to one value. Counting the elements that satisfy a condition is the most common case.

vectorized.R
scores <- c(72, 85, 60, 90)
cat("pass count:", sum(scores >= 70), "\n")
cat("average:", mean(scores), "\n")

The expression scores >= 70 produces four logical values, and sum adds them as ones and zeros. A loop would need a counter, a test, and an increment; the vectorised version states the question directly. Keep a loop for the cases where one iteration depends on the result of the previous one, such as the simulation below.

$ Rscript vectorized.R
pass count: 3 
average: 76.75 

A complete example

The Collatz sequence starts with a positive integer and applies one of two rules: an even number is halved, and an odd number is multiplied by three and then increased by one. The conjecture is that every starting value eventually reaches one. The next script counts the steps for the starting value 27, which is famous for its long sequence.

collatz.R
n <- 27
steps <- 0
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- 3 * n + 1
  }
  steps <- steps + 1
}
cat("steps:", steps, "\n")

The loop keeps running while n differs from one. The if chooses the rule, and the counter increases once per iteration regardless of which branch ran. Starting at 27, the sequence reaches one after 111 steps, after climbing above nine thousand on the way. The same pattern of a condition, two branches, and a counter appears in simulations, games, and numerical algorithms.

$ Rscript collatz.R
steps: 111 

Next steps

The next article introduces functions, which package a block of statements under a name and give it parameters. Once functions exist, the loops and branches in this article can be reused without copying them, and the apply-family article later in the series shows how to replace many loops with a single function call.

Source

The R Language Definition: control structures

An Introduction to R: grouped expressions

R documentation: ifelse

R documentation: control flow

In this article we have branched with if, else, and else if, applied a condition to a whole vector with ifelse, and repeated work with for, while, and repeat. We used break to leave a loop, next to skip an iteration, and switch to select an alternative. The series continues with R functions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.