12 Conditional statements
12.1 If
Format: if (condition) statement
- condition: expression returning a logic value (
TRUE
orFALSE
) - statement: any valid R statement
- statement only executed if condition is
TRUE
## Negative
12.2 Else
Format: if (condition) statement1 else statement2
- condition: expression returning a logic value (
TRUE
orFALSE
) - statement1 and statement2: any valid R statements
- statement1 executed if condition is
TRUE
- statement2 executed if condition is
FALSE
## Negative
## Positive
12.3 Code blocks
Suppose you want to execute several statements within a function, or if a condition is true
- Such a group of statements are called code blocks
{
and}
contain code blocks
first_value <- 8
second_value <- 5
if (first_value > second_value) {
cat("First is greater than second\n")
difference <- first_value - second_value
cat("Their difference is ", difference)
}
## First is greater than second
## Their difference is 3