Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove words in one column present in another column in R

Tags:

regex

dataframe

r

I have a dataframe that is in this format:

A <- c("John Smith", "Red Shirt", "Family values are better")
B <- c("John is a very highly smart guy", "We tried the tea but didn't enjoy it at all", "Family is very important as it gives you values")

df <- as.data.frame(A, B)

My intention is to get the result back as:

ID   A                           B
1    John Smith                  is a very highly smart guy
2    Red Shirt                   We tried the tea but didn't enjoy it at all
3    Family values are better    is very important as it gives you

I have tried:

test<-df %>% filter(sapply(1:nrow(.), function(i) grepl(A[i], B[i])))

But it doesn't give me what I want.

Any suggestions/help?

like image 765
Srinivasan Iyer Avatar asked Apr 20 '18 20:04

Srinivasan Iyer


2 Answers

One solution is to use mapply along with strsplit.

The trick is to split df$A in separate words and collapse those words separated by | and then use it as pattern in gsub to replace with "".

lst <- strsplit(df$A, split = " ")

df$B <- mapply(function(x,y){gsub(paste0(x,collapse = "|"), "",df$B[y])},lst,1:length(lst))
df
# A                                           B
# 1               John Smith                  is a very highly smart guy
# 2                Red Shirt We tried the tea but didn't enjoy it at all
# 3 Family values are better          is very important as it gives you 

Another option is as:

df$B <- mapply(function(x,y)gsub(x,"",y) ,gsub(" ", "|",df$A),df$B)

Data:

A <- c("John Smith", "Red Shirt", "Family values are better")
B <- c("John is a very highly smart guy", "We tried the tea but didn't enjoy it at all", "Family is very important as it gives you values")

df <- data.frame(A, B, stringsAsFactors = FALSE)
like image 140
MKR Avatar answered Nov 09 '22 19:11

MKR


Just another option using stringr::str_split_fixed function:

library(stringr)

str_split_fixed(sapply(paste(df$A,df$B, sep=" columnbreaker "), 
                function(i){
                            paste(unique(
                                         strsplit(as.character(i), split=" ")[[1]]), 
                         collapse = " ")}), 
                 " columnbreaker ", 2)


#       [,1]                       [,2]                                         
# [1,] "John Smith"               "is a very highly smart guy"                 
# [2,] "Red Shirt"                "We tried the tea but didn't enjoy it at all"
# [3,] "Family values are better" "is very important as it gives you"  
like image 21
M-- Avatar answered Nov 09 '22 20:11

M--