首页 > 解决方案 > 如何将特定单词替换为R中的另一个单词

问题描述

我正在寻找 gsub 中的代码以将特定单词替换为 xx 像这样。

x <- c("replace #bitcoin and not #bitoinusdha", "replace #btc and not #btcasdasd")

View(x)
[1] replace  xx and not #bitcoinusdha
[2] replace xx and not #btcasdasd

希望有人可以帮助我。

问候,

奥托

标签: r

解决方案


假设要替换的短语始终以 开头#abc...,然后在每个模式的末尾使用单词边界并搜索任一值。

x <- c("replace #bitcoin and not #bitcoinusdha", "replace #btc and not #btcasdasd")
gsub("#bitcoin\\b|#btc\\b", "xx", x)
#> [1] "replace xx and not #bitcoinusdha" "replace xx and not #btcasdasd"

推荐阅读