Multiple replacement in R

r
data_science

#1

Hi,

I am trying to do multiple replacement with single function.
I want to replace some words with 1 category word
For example:
“Scrubs & Body Treatments”,"Exfoliators, Polishes & Scrubs ",“Scrubs & Body Treatments” these three words and now I want replace there name with "Scrub"
I tried to create function as follows:
myfun <- function(pattern,replacement,x){
result <- list()
for (i in 1:length(pattern)) {
result[i] <- gsub(pattern[i],replacement,x)
}
result
}
but its not working.
Thanks in Advance


#2

Hello.

You may use some function similar to:

x<-c("Scrubs & Body Treatments","Exfoliators, Polishes & Scrubs ","Scrubs & Body Treatments", "Another stuff")

y<-x
for(s in 1:length(x))
{
    if(grepl(x=x[s], pattern='Scrubs')) y[s]<-'Scrub'
}

y

I hope this help!


#3

Thank you for you reply