Using map2 inside case_when to replace strings

Viewed 190

I have a 2 column tibble, replace_tbl, that has a vector of patterns and a vector of replacements in it. I want to use the values in those columns to create a new variable in a different tibble, df, that, for each row in df will loop through the values of replace_tbl$pat and, if detected, will replace with replace_tbl$replace. If the pattern is not detected, it should return NA.

My sense is I should be using some combination of mutate(), map2(), and case_when(), but I can't figure it out. Essentially I'd like to do what the code below accomplishes, but without having to duplicate the str_detect() call multiple times.

library(tidyverse)

replace_tbl <- tibble(
  pattern = c("Ideal|Premium", "Very Good"),
  replace = c("Apple", "Banana")
)

#what I want to replicate
diamonds %>%
  mutate(new_var = case_when(
    str_detect(cut, replace_tbl$pattern[[1]]) ~ replace_tbl$replace[[1]],
    str_detect(cut, replace_tbl$pattern[[2]]) ~ replace_tbl$replace[[2]],
    TRUE ~ NA_character_
  )) %>%
  head()

# A tibble: 6 x 11
  carat cut       color clarity depth table price     x     y     z new_var
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>  
1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43 Apple  
2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31 Apple  
3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31 NA     
4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63 Apple  
5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75 NA     
6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48 Banana 
1 Answers

You can use the fuzzyjoin package:

library(fuzzyjoin)
diamonds %>%
  as_tibble() %>% 
  regex_left_join(replace_tbl, by = c(cut = "pattern"))

# A tibble: 53,940 x 12
   carat cut       color clarity depth table price     x     y     z pattern       replace
   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>         <chr>  
 1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43 Ideal|Premium Apple  
 2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31 Ideal|Premium Apple  
 3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31 NA            NA     
 4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63 Ideal|Premium Apple  
 5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75 NA            NA     
 6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48 Very Good     Banana 

You already did the seperation with | which controls the different regex patterns.

Related