R: Cut equivalent for strings

Viewed 42

I have a list of different types of masks and I would like to categorise them into those that are N95, surgical, cloth or other.

     df<-data.frame(mask_type=
c("Surgical Mask (3M 1800)",                                                                      
     "N95 FFR (Wilson 1105N) (2x 3mm leaks)",                                                        
     "N95 FFR (San Huei United Company 1895N) (2x 3mm leaks)",                                       
     "Surgical Mask (Primed  PG4-1073) (2x 3mm leaks)",                                              
     "Surgical Mask (3M 1800) (2x 3mm leaks)",                                                       
     "N95 FFR (Wilson 1105N) (4x 3mm leaks)",                                                        
     "Cloth FFR (San Huei United Company 1895N) (4x 3mm leaks)",                                       
     "Cloth Mask (Primed  PG4-1073) (4x 3mm leaks)") 

This works that filters the masks but doesn't create an "other" column. Am I far away do you think?

require(dplyr) require(tidyr)

df %>%
  mutate(TYPE=stringr::str_detect(mask_type,"N95 | surgical | cloth")) %>%
  filter(TYPE=TRUE) %>%
  select(mask_type)
2 Answers

Use str_extract to extract if any of the pattern 'Surgical|N95|Cloth' is present in the string. If none of it is present it will return NA which can be replaced with 'Other'.

library(dplyr)
library(stringr)

df %>%
  mutate(TYPE= str_extract(mask_type, regex('Surgical|N95|Cloth', ignore_case = TRUE)), 
         TYPE = replace(TYPE, is.na(TYPE), 'Other'))

We can use base R

lst1 <- with(df, regmatches(mask_type, gregexpr('Surgical|N95|Cloth', mask_type)))
df$TYPE <- sapply(lst1, function(x) if(length(x) == 0) 'Other' else x)
Related