R remove multiple text strings in data frame

gsub, keyword, r

Solution

wordstoremove <- c("ai", "computing", "ulitzer", "ibm", "privacy", "cognitive")

(dat <- read.table(header = TRUE, text = 'id text time username
1 "ai and x" 10 "me"
2 "and computing" 5 "you"
3 "nothing" 15 "everyone"
4 "ibm privacy" 0 "know"'))

#   id          text time username
# 1  1      ai and x   10       me
# 2  2 and computing    5      you
# 3  3       nothing   15 everyone
# 4  4   ibm privacy    0     know

(dat1 <- as.data.frame(sapply(dat, function(x) 
  gsub(paste(wordstoremove, collapse = '|'), '', x))))

#   id    text time username
# 1  1   and x   10       me
# 2  2    and     5      you
# 3  3 nothing   15 everyone
# 4  4            0     know

Problem

New to R. I am looking to remove certain words from a data frame. Since there are multiple words, I would like to define this list of words as a string, and use gsub to remove. Then convert back to a dataframe and maintain same structure. ``` wordstoremove <- c("ai", "computing", "ulitzer", "ibm", "privacy", "cognitive") a id text time username 1 "ai and x" 10 "me" 2 "and computing" 5 "you" 3 "nothing" 15 "everyone" 4 "ibm privacy" 0 "know" ``` I was thinking something like: ``` a2 <- apply(a, 1, gsub(wordstoremove, "", a) ``` but clearly this doesnt work, before converting back to a data frame.

Original source