> 26
value_1 == "some character data" value_2
Conditionals (reference card)
Conditional statements
Basic conditional statements
Checking if a value is in a vector
%in% c(1, 2, 3) value_1
Functions that return logical/boolean values
E.g., is.na()
will return TRUE
if the value is NA
and FALSE
otherwise
is.na(value_1)
Reversing conditions
!
is used to reverse a condition- Enclose the condition in
!()
- E.g., to get
TRUE
ifvalue_1
is not inc(1, 2, 3)
!(value_1 %in% c(1, 2, 3))
Combining conditions
- Using
&
will returnTRUE
if both conditions areTRUE
> 26 & value_1 < 30 value_1
- Using
|
will returnTRUE
if at least one condition isTRUE
> 26 | value_2 == "some character data" value_1
Conditional statements on vectors
Conditional statements work elementwise on vectors.
c(1, 2, 3, 4, 5) > 2
1] FALSE FALSE TRUE TRUE TRUE [
This is also true for (many) functions that return logical values.
is.na(c(1, 2, NA, 4, 5))
1] FALSE FALSE TRUE FALSE FALSE [
if
statements
Check to see if the condition is TRUE
and if so run the code in the code block.
if (value_1 == "A") {
<- 42
result }
Can check multiple conditions using else if
.
if (value_1 == "A") {
<- 42
result else if (value_1 == "B") {
} <- 26
result }
else
can be used to run code if none of the conditions are TRUE
.
if (value_1 == "A") {
<- 42
result else if (value_1 == "B") {
} <- 26
result else {
} <- NA
result }
Nested if
statements
If one if
statement is placed inside of another if
statement the outer if
statement is checked first. If the associated condition is TRUE
then the inner if
statement is checked.
if (value_1 == "A") {
if (value_2 > 10) {
<- 42
result else if (value_2 < 5) {
} <- 26
result
} }
The conditions related to value_2
will only be checked if value_1
is "A"
.