将包含特定单词的字符串替换为该单词

时间:2020-05-04 21:30:51

标签: r text replace

我在df中有一列,其中包含许多不同的字符串,例如,一个字符串会说在点a处交叉或通过点a进入。我只想用a替换整个字符串,我该怎么做呢?

1 个答案:

答案 0 :(得分:2)

comment用户对问题进行Allan Cameron之后,这是我提出的建议的完整解决方案。

df1 <- data.frame(col = c("crossed at point a", 
                          "doesn't match though it has as", 
                          "came in through point a", 
                          "no"))

df1$col[grepl("\\ba\\b", df1$col)] <- "a"
df1
#                              col
#1                               a
#2  doesn't match though it has as
#3                               a
#4                              no

编辑

在艾伦·卡梅隆(Allan Cameron)的另一个comment之后,我决定编写一个小函数,以使其更容易用该单词替换包含该单词的字符串。

replaceWord <- function(x, word){
  pattern <- paste0("\\b", word, "\\b")
  i <- grep(pattern, x)
  x[i] <- word
  x
}

replaceWord(df1$col, "a")