R的新知识。我希望从数据帧中删除某些单词。因为有多个单词,所以我想将这个单词列表定义为一个字符串,并使用gsub删除。然后转换回数据帧并保持相同的结构。
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" 我是这样想的:
a2 <- apply(a, 1, gsub(wordstoremove, "", a)但很明显,在转换回数据帧之前,这并不起作用。
发布于 2014-07-09 12:46:00
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发布于 2018-05-04 05:50:14
使用dplyr::mutate()和stringr::str_remove_all()的另一种选择
library(dplyr)
library(stringr)
dat <- dat %>%
mutate(text = str_remove_all(text, regex(str_c("\\b",wordstoremove, "\\b", collapse = '|'), ignore_case = T)))因为小写的“ai”很容易成为较长单词的一部分,所以要删除的单词与\\b绑定在一起,这样它们就不会从开头、中间或结尾或其他单词中删除。
搜索模式也用regex(pattern, ignore_case = T)包装,以防文本字符串中的某些单词大写。
如果您想要将单词替换为其他内容,而不是简单地删除它们,则可以使用str_replace_all()。str_remove_all()只是str_replace_all(string, pattern, '')的一个别名。
rawr的anwswer可以更新为:
dat1 <- as.data.frame(sapply(dat, function(x)
gsub(paste0('\\b', wordstoremove, '\\b', collapse = '|'), '', x, ignore.case = T)))https://stackoverflow.com/questions/24645390
复制相似问题