[英]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
. 在这里,我想改变sp
为indet
而不改变其他词,例如species
。
names <- c ('sp', 'sprucei', 'sp', 'species')
I have tried gsub
but when I run it the output is not as I wanted 我尝试过gsub
但是当我运行它时输出不是我想要的
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 如果在sp
之前/之后还有其他单词,则可以使用\\b
代替单词边界
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'
与MrFlick的解决方案不同,如果在'sp'
之前或之后有空格或单词,则此方法将无效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.