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:

if ()`condition`

else`true_expression`

`false_expression`

or, alternatively:

if ()`condition`

`expression`

Because the expressions

,
`expression`

,
and `true_expression`

are not always evaluated, the function `false_expression`

`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

statement
is a vector of more than one `condition`

`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] ...

Start Free Trial

No credit card required