Search code examples
rtidyversecase

How can I use `case_when` to conditionally change a value based on string detection and current column values in R?


I'm trying to conditionally change values in a column based on not detecting a string and the current values in the column.

starwars %>%
  mutate(
    species = case_when(
      !str_detect(name, "Luke Skywalker") |
        !str_detect(name, "LUKE SKYWALKER") |
        !str_detect(name, "Darth Vader") |
        !str_detect(name, "DARTH VADER") &
        species == "Human"
      ~ "Other",
      .default = species
    )
  )

The result is that all values for species become "Other". I would have expected just the human characters (who are not Luke Skywalker or Darth Vader) to be "Other for species.


Solution

  • Since you only have two conditions in your mutate command, you don't even need case_when() - you can just use if_else().

    Here's an easy way to combine your conditions:

    library(tidyverse)
    
    starwars %>%
      mutate(species = if_else(!name %in% c("Luke Skywalker", "Darth Vader") &
                               species == "Human", "Other", species))
    #> # A tibble: 87 × 14
    #>    name     height  mass hair_color skin_color eye_color birth_year sex   gender
    #>    <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
    #>  1 Luke Sk…    172    77 blond      fair       blue            19   male  mascu…
    #>  2 C-3PO       167    75 <NA>       gold       yellow         112   none  mascu…
    #>  3 R2-D2        96    32 <NA>       white, bl… red             33   none  mascu…
    #>  4 Darth V…    202   136 none       white      yellow          41.9 male  mascu…
    #>  5 Leia Or…    150    49 brown      light      brown           19   fema… femin…
    #>  6 Owen La…    178   120 brown, gr… light      blue            52   male  mascu…
    #>  7 Beru Wh…    165    75 brown      light      blue            47   fema… femin…
    #>  8 R5-D4        97    32 <NA>       white, red red             NA   none  mascu…
    #>  9 Biggs D…    183    84 black      light      brown           24   male  mascu…
    #> 10 Obi-Wan…    182    77 auburn, w… fair       blue-gray       57   male  mascu…
    #> # ℹ 77 more rows
    #> # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
    #> #   vehicles <list>, starships <list>
    

    Created on 2023-05-19 with reprex v2.0.2