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_expressionelsefalse_expression
or, alternatively:
if (condition)expression
Because the expressions ,
expression,
and true_expression
are not always evaluated, the function false_expressionif 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] 5In R, conditional statements are not vector operations. If the
statement is a vector of more than one conditionlogical value, 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] "a" "b" "a" "b" "a" ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access