Conditionals (reference card)

Conditional statements

Basic conditional statements

value_1 > 26
value_2 == "some character data"

Checking if a value is in a vector

value_1 %in% c(1, 2, 3)

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 if value_1 is not in c(1, 2, 3)
!(value_1 %in% c(1, 2, 3))

Combining conditions

  • Using & will return TRUE if both conditions are TRUE
value_1 > 26 & value_1 < 30
  • Using | will return TRUE if at least one condition is TRUE
value_1 > 26 | value_2 == "some character data"

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") {
  result <- 42
}

Can check multiple conditions using else if.

if (value_1 == "A") {
  result <- 42
} else if (value_1 == "B") {
  result <- 26
}

else can be used to run code if none of the conditions are TRUE.

if (value_1 == "A") {
  result <- 42
} else if (value_1 == "B") {
  result <- 26
} else {
  result <- NA
}

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) {
    result <- 42
  } else if (value_2 < 5) {
    result <- 26
  }
}

The conditions related to value_2 will only be checked if value_1 is "A".