You can just collapse your search words into a regex string.
Test <- 'This is an example text testing [] test'
top <- "This"
bottom <- "test"
arg <- c(top, bottom)
arg <- paste(arg, collapse="|")
arg <- gsub("(\\w+)", "\\\\b\\1\\\\b", arg)
Test.c <- gsub(arg, "", Test)
Test.c <- gsub("[ ]+", " ", Test.c)
Test.c <- gsub("^[[:space:]]|[[:space:]]$", "", Test.c)
Test.c
# "is an example text []"
Or using magrittr
pipes
library(magrittr)
c(top, bottom) %>%
paste(collapse="|") %>%
gsub("(\\w+)", "\\\\b\\1\\\\b", .) %>%
gsub(., "", Test) %>%
gsub("[ ]+", " ", .) %>%
gsub("^[[:space:]]|[[:space:]]$", "", .) -> Test.c
Test.c
# "is an example text []"
Or using a loop
Test.c <- Test
words <- c(top, bottom)
for (i in words) {
Test.c <- gsub(paste0("\\\\b", i, "\\\\b"), "", Test)
}
Test.c <- gsub("[ ]+", " ", Test.c)
Test.c <- gsub("^[[:space:]]|[[:space:]]$", "", Test.c)
Test.c
# "is an example text []"