首页 > 解决方案 > 将包含某个单词的字符串替换为该单词

问题描述

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

标签: rtextreplace

解决方案


Following a comment to the question by user Allan Cameron, here is a full solution with the suggestion I made.

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

Edit

Following another comment by Allan Cameron I have decided to write a small function to make it easier to replace a string that contains a word by that word.

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

replaceWord(df1$col, "a")

推荐阅读