Home > database >  Matching Character Strings that are Not Exact Matches in R
Matching Character Strings that are Not Exact Matches in R

Time:07-12

Consider the following dataframe named estimates_df.

....
                                Item            section
7596                5 Gal Samandoque      Cacti/Accents
7597       5 Gal Purple Prickly Pear      Cacti/Accents
7598              5 Gal Banana Yucca      Cacti/Accents
7599                5 Gal Yucca Vine              Vines
7600             5 Gal Red Three Awn            Grasses
7601 3/4" Screened To Match Existing      Decomposed Granite
...

I also have a character vector with cactus/succulent names named cactus_names.

[1]"Prickly Pear"
[2]"Samandoque"
[3]"Banana Yucca"
...

I do not want to alter the full name in the Item column, but I want to change the section column based on the names that appear in my cactus/succulent vector. I am having difficulty doing this because the names in the vector do not exactly match the names in the column. For example, I have tried to do something like this:

estimates_df %>%
mutate(section = ifelse(cactus_names %in% Item, "Cacti/Succulents", section)

Obviously, this does not match any of the names because they do not match exactly. I want the end result to look like so:

....
                                Item            section
7596                5 Gal Samandoque      Cacti/Succulents
7597       5 Gal Purple Prickly Pear      Cacti/Succulents
7598              5 Gal Banana Yucca      Cacti/Succulents
7599                5 Gal Yucca Vine              Vines
7600             5 Gal Red Three Awn            Grasses
7601 3/4" Screened To Match Existing      Decomposed Granite
...

CodePudding user response:

Are you looking for something like this!

library(dplyr)
library(stringr)

cactus_names <- c("Prickly Pear", "Yucca Vine", "Banana Yucca")

pattern <- paste(cactus_names, collapse = "|")

df %>% 
  mutate(section = ifelse(str_detect(Item, pattern), "Cacti/Succulents", section))

    id                           Item            section
1 7596               5 Gal Samandoque      Cacti/Accents
2 7597      5 Gal Purple Prickly Pear   Cacti/Succulents
3 7598             5 Gal Banana Yucca   Cacti/Succulents
4 7599               5 Gal Yucca Vine   Cacti/Succulents
5 7600            5 Gal Red Three Awn            Grasses
6 7601 3/4 Screened To Match Existing Decomposed Granite
  • Related