Changing and creating variables with case_when()

Categorical Data in the Tidyverse

Emily Robinson

Data Scientist

case_when()

x <- 1:20
x
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
case_when(x %% 15 == 0 ~ "fizz buzz", 
          x %% 3 == 0 ~ "fizz", 
          x %% 5 == 0 ~ "buzz", 
          TRUE ~ as.character(x) )
 [1] "1"         "2"         "fizz"      "4"        
 [5] "buzz"      "fizz"      "7"         "8"        
 [9] "fizz"      "buzz"      "11"        "fizz"     
[13] "13"        "14"        "fizz buzz" "16"       
[17] "17"        "fizz"      "19"        "buzz"
Categorical Data in the Tidyverse

Order matters

case_when(x %% 3 == 0 ~ "fizz buzz", 
          x %% 5 == 0 ~ "buzz", 
          x %% 3 == 0 ~ "fuzzy buzz",
          TRUE ~ as.character(x) )
 [1] "1"         "2"         "fizz buzz" "4"        
 [5] "buzz"      "fizz buzz" "7"         "8"        
 [9] "fizz buzz" "buzz"      "11"        "fizz buzz"
[13] "13"        "14"        "fizz buzz" "16"       
[17] "17"        "fizz buzz" "19"        "buzz"
Categorical Data in the Tidyverse

case_when() with multiple variables

> moods
# A tibble: 4 x 2
  mood  status       
  <chr> <chr>        
1 happy know it      
2 happy do not know it
3 sad   know it      
4 happy know it      
moods %>%
  mutate(action = case_when(
  mood == "happy" & status == "know it" ~ "clap your hands",
   mood == "happy" & status == "do not know it" ~ "stomp your feet", 
   mood == "sad" ~ "look at puppies", 
   TRUE ~ "jump around")
Categorical Data in the Tidyverse

Let's practice!

Categorical Data in the Tidyverse

Preparing Video For Download...