Making gsub only replace entire words?

ぃ、小莉子 提交于 2019-11-29 06:24:48

You are so close to getting this. You're already using paste to form the replacement string, why not use it to form the pattern string?

goodwords.corpus <- c("good")
test <- "I am having a good time goodnight"
for (i in 1:length(goodwords.corpus)){
    test <-gsub(paste0('\\<', goodwords.corpus[[i]], '\\>'), paste(goodwords.corpus[[i]], "1234"), test)
}
test
# [1] "I am having a good 1234 time goodnight"

(paste0 is merely paste(..., sep='').)

(I posted this the same time as @MatthewLundberg, and his is also correct. I'm actually more familiar with using \b vice \<, but I thought I'd continue with using your code.)

Use \b to indicate a word boundary:

> text <- "good night goodnight"
> gsub("\\bgood\\b", paste("good", 1234), text)
[1] "good 1234 night goodnight"

In your loop, something like this:

for (word in goodwords.corpus){
  patt <- paste0('\\b', word, '\\b')
  repl <- paste(word, "1234")

  test <-gsub(patt, repl, test)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!