Control Structures

Nearly every operation in R can be written as a function, but it isn’t always convenient to do so. Therefore, R provides special syntax that you can use in common program structures. We’ve already described two important sets of constructions: operators and grouping brackets. This section describes a few other key language structures and explains what they do.

Conditional Statements

Conditional statements take the form:

if (condition) true_expression else false_expression

or, alternatively:

if (condition) expression

Because the expressions expression, true_expression, and false_expression are not always evaluated, the function if has the type special:

> typeof(`if`)
[1] "special"

Here are a few examples of conditional statements:

> if (FALSE) "this will not be printed"
> if (FALSE) "this will not be printed" else "this will be printed"
[1] "this will be printed"
> if (is(x, "numeric")) x/2 else print("x is not numeric")
[1] 5

In R, conditional statements are not vector operations. If the condition statement is a vector of more than one logical value, then only the first item will be used. For example:

> x <- 10
> y <- c(8, 10, 12, 3, 17)
> if (x < y) x else y
[1]  8 10 12  3 17
Warning message:
In if (x < y) x else y :
  the condition has length > 1 and only the first element will be used

If you would like a vector operation, use the ifelse function instead:

> a <- c("a", "a", "a", "a", "a")
> b <- c("b", "b", "b", "b", "b")
> ifelse(c(TRUE, FALSE, TRUE, FALSE, TRUE), a, b) [1] ...

Get R in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.