我在df中有一列,其中包含许多不同的字符串,例如,一个字符串会说在点a处交叉或通过点a进入。我只想用a替换整个字符串,我该怎么做呢?
答案 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")