简体   繁体   中英

Replacing text in R without changing other words

I want to replace certain terms without changing other words. Here I want to change sp for indet without changing other words, such as species .

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

I have tried gsub but when I run it the output is not as I wanted

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

output:

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

and not:

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

Any advice? Cheers!

Try

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

the ^ requires the match to begin at the start of the string and the $ requires it to end at the end of the string.

If you had other words before/after the sp , you could use \\b to match word boundaries instead

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

Another option, given your example, is this:

names <- c ('sp', 'sprucei', 'sp', 'species')
names[names=='sp'] <- 'indet'
names
# [1] "indet"   "sprucei" "indet"   "species"

Unlike MrFlick's solution, this won't work if there are spaces or words before or after 'sp'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM