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
}

if statements need a single TRUE or FALSE value, so they don’t work elementwise on vectors the way conditional statements do.

Using functions that return logical values

Any function that returns a single TRUE or FALSE can be used as the condition in an if statement. E.g., str_detect() from stringr returns TRUE if a string contains a pattern.

library(stringr)

if (str_detect(value_1, "A")) {
  result <- 42
}

Conditionals inside functions

Place the if statement inside the function and pass in any values used in the conditions as arguments. return() the result after the if statement so that whichever block ran determines what is returned.

function_name <- function(input_1, input_2){
  if (input_2 == "A") {
    output_value <- input_1 * 42
  } else if (input_2 == "B") {
    output_value <- input_1 * 26
  } else {
    output_value <- NA
  }
  return(output_value)
}