替换R中的文本而不更改其他单词

AEM*_*AEM 2 replace r gsub

我想在不改变其他词的情况下替换某些术语.在这里,我想改变spindet不改变换句话说,如species.

names <- c ('sp', 'sprucei', 'sp', 'species')

我试过gsub但是当我运行它时输出不是我想要的

gsub (' sp', ' indet', names)

输出:

[1] "indet" "indetrucei" "indet" "indetecies"

并不是:

[1] "indet" "sptrucei" "indet" "sptecies"

有什么建议?干杯!

MrF*_*ick 6

尝试

names <- c ('sp', 'sprucei', 'sp', 'species')
gsub('^sp$', 'indet', names)
# [1] "indet"   "sprucei" "indet"   "species"
Run Code Online (Sandbox Code Playgroud)

^需要比赛开始字符串的开始和$要求它在字符串的结尾结束.

如果您在之前/之后有其他单词sp,则可以使用\b匹配单词边界

names <- c ('sp', 'sprucei', 'apple sp banana', 'species')
gsub('\\bsp\\b', 'indet', names)
# [1] "indet"       "sprucei"       "apple indet banana"     "species"
Run Code Online (Sandbox Code Playgroud)