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 take the form:
Because the expressions
are not always evaluated, the function
if has the type
> typeof(`if`)  "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"  "this will be printed" > if (is(x, "numeric")) x/2 else print("x is not numeric")  5
In R, conditional statements are not vector operations. If the
is a vector of more than one
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  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,
> a <- c("a", "a", "a", "a", "a") > b <- c("b", "b", "b", "b", "b") > ifelse(c(TRUE, FALSE, TRUE, FALSE, TRUE), a, b)  ...