if_else( )

Choose one value when a condition is TRUE and another when it is FALSE. if_else() is from the dplyr package, which is part of the tidyverse.

Required Library

install.packages("tidyverse")
library(tidyverse)

Syntax

if_else(condition, true, false)

if_else() is a vectorised if/else function. For every value in condition, it returns the matching value from true or false.

df %>% mutate(new_col = if_else(condition, true_value, false_value))

if_else() works especially well inside mutate() when you want to create a new column based on a condition.

Use if_else() when you need a row-by-row choice between two values. It is a clean way to do conditional calculations inside mutate().

Base if works on a single TRUE/FALSE value. if_else() is vectorised, so it can make a choice for every row in a column.

Examples

Classify tablet weights as pass or fail
Correct dilution only for specific samples

Argument Overview

Required arguments must be included when using a function while optional arguments can be included on demand.

condition logical vector Required

A logical test that is evaluated row by row.

abs(weight_mg - 500) <= 15

Data Types: logical

true vector Required

Values returned when condition is TRUE.

if_else(abs(weight_mg - 500) <= 15, "pass", "fail")

Data Types: any vector type that matches the output type

false vector Required

Values returned when condition is FALSE.

Data Types: any vector type that matches the output type

missing vector Optional

Value used when condition is NA. If omitted, missing values in the condition stay missing in the result.

Data Types: any vector type that matches the output type · Default: NULL