remove list of strings from string column in R

Viewed 197

I have a dataframe like so:

df = data.frame('name' = c('California parks', 'bear lake', 'beautiful tree house', 'banana plant'), 'extract' = c('parks', 'bear', 'tree', 'plant'))

How do I remove the strings of the 'extract' column from the name column to get the following result:

name_new = California, lake, beautiful house, banana

I'm suspecting this demands a combination of str_extract and lapply but can quite figure it out.

Thanks!

2 Answers

The str_remove or str_replace are vectorized for both string and pattern. So, if we have two columns, just pass those columns 'name', 'extract' as the string, pattern to remove the substring in the 'name' column elementwise. Once we remove those substring, there are chances of having spaces before or after which can be removed or replaced with str_replace with trimws (to remove the leading/lagging spaces)

library(dplyr)
library(stringr)
df %>% 
    mutate(name_new = str_remove(name, extract),
        name_new = str_replace_all(trimws(name_new), "\\s{2,}", " "))
#                 name extract        name_new
#1     California parks   parks      California
#2            bear lake    bear            lake
#3 beautiful tree house    tree beautiful house
#4         banana plant   plant          banana

A base R option using gsub + Vectorize

within(df,name_new <- Vectorize(gsub)(paste0("\\s",extract,"\\s")," ",name))

which gives

                  name extract        name_new
1     California parks   parks      California
2            bear lake    bear            lake
3 beautiful tree house    tree beautiful house
4         banana plant   plant          banana
Related