replace multiple words in a string in R
Code snippet on how to replace multiple words in a string in R
# Function to replace multiple words in a string
replaceMultiple <- function(x, names) {
for(name in names) {
x <- gsub(paste0("\\b",name,"\\b"), "", x, ignore.case = TRUE)
}
return(x)
}
This code creates a function that replaces multiple words from a string. The function takes two parameters, x which is the string to be modified and names which is a vector of strings that need to be replaced. The for loop iterates through the names vector and applies the gsub function on the x string each time. The gsub function looks for exact matches of the name in the x string with ‘\b’ signifying word boundaries and replaces the matching strings with an empty character, "". The ignore.case = TRUE parameter is used to ignore cases while searching and replacing. The modified x string is returned as the result of the function.