用该词替换包含某个词的字符串。

问题描述 投票:0回答:1

在我的DF中,有一列有很多不同的字符串,比如一串会说在a点交叉,或者从a点进来,我想把整个字符串只替换成a,我该怎么做?

r text replace
1个回答
2
投票

跟随一个 评论 对用户提出的问题 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 我决定写一个小函数,让包含一个单词的字符串更容易被该单词取代。

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

replaceWord(df1$col, "a")
© www.soinside.com 2019 - 2024. All rights reserved.