dplyr::case_when()
   get_help() docs


Description

The case_when() function is part of the {dplyr} package, which is part of the {tidyverse}.

We use this function to recode a variable to different values. The case_when() function can be used when there are more than two conditions for recoding, in which case if_else() would be appropriate. We often use case_when() along with mutate() to create new data frame columns.

Be patient with the case_when() syntax: It is tricky!

To use this function, you need to either first load the {dplyr} library, or always use the function with dplyr::case_when() notation.

# Load the library
library(dplyr)
# Or, load the full tidyverse:
library(tidyverse)

# Or, use :: notation
dplyr::case_when()

Conceptual Usage

case_when(a logical statement ~ return this value if this statement is TRUE,
          a different logical statement ~ return this value if this statement is TRUE,
          yet another logical statement ~ return this value if this statement is TRUE,
          (...as many as you need...)
          # optional
          TRUE ~ value to return if condition was not ever met)

Examples

The example below uses the carnivores dataset. Learn more about this dataset with get_help("carnivores").

# Show the carnivores dataset
carnivores
## # A tibble: 9 × 4
##   name              genus        awake brainwt
##   <chr>             <fct>        <dbl>   <dbl>
## 1 Arctic fox        Vulpes        11.5  0.0445
## 2 Cheetah           Acinonyx      11.9 NA     
## 3 Dog               Canis         13.9  0.07  
## 4 Gray seal         Haliochoerus  17.8  0.325 
## 5 Jaguar            Panthera      13.6  0.157 
## 6 Lion              Panthera      10.5 NA     
## 7 Northern fur seal Callorhinus   15.3 NA     
## 8 Red fox           Vulpes        14.2  0.0504
## 9 Tiger             Panthera       8.2 NA


# Use case_when to help create a new column called `how_awake` in `carnivores` that will be:
## "alert" if awake >= 16
## "medium" if awake < 16 and awake > 10
## "sleepy" if awake <= 10
carnivores %>%
  mutate(how_awake = case_when(
          # Spacing out code like this makes it easier to see, write, and use.
          awake >= 16 ~ 'alert',
          awake < 16 & awake > 10 ~ 'medium',
          awake <= 10 ~ 'sleepy')
    )
## # A tibble: 9 × 5
##   name              genus        awake brainwt how_awake
##   <chr>             <fct>        <dbl>   <dbl> <chr>    
## 1 Arctic fox        Vulpes        11.5  0.0445 medium   
## 2 Cheetah           Acinonyx      11.9 NA      medium   
## 3 Dog               Canis         13.9  0.07   medium   
## 4 Gray seal         Haliochoerus  17.8  0.325  alert    
## 5 Jaguar            Panthera      13.6  0.157  medium   
## 6 Lion              Panthera      10.5 NA      medium   
## 7 Northern fur seal Callorhinus   15.3 NA      medium   
## 8 Red fox           Vulpes        14.2  0.0504 medium   
## 9 Tiger             Panthera       8.2 NA      sleepy