![](/img/trans.png)
[英]Changing spelling for multiple words at a time in R/replacing many words at once
[英]Replacing text in R without changing other words
我想在不改变其他词的情况下替换某些术语。 在这里,我想改变sp
为indet
而不改变其他词,例如species
。
names <- c ('sp', 'sprucei', 'sp', 'species')
我尝试过gsub
但是当我运行它时输出不是我想要的
gsub (' sp', ' indet', names)
输出:
[1] "indet" "indetrucei" "indet" "indetecies"
并不是:
[1] "indet" "sptrucei" "indet" "sptecies"
有什么建议? 干杯!
尝试
names <- c ('sp', 'sprucei', 'sp', 'species')
gsub('^sp$', 'indet', names)
# [1] "indet" "sprucei" "indet" "species"
^
要求匹配从字符串的开头开始, $
要求它在字符串的结尾处结束。
如果在sp
之前/之后还有其他单词,则可以使用\\b
代替单词边界
names <- c ('sp', 'sprucei', 'apple sp banana', 'species')
gsub('\\bsp\\b', 'indet', names)
# [1] "indet" "sprucei" "apple indet banana" "species"
根据您的示例,另一个选项是:
names <- c ('sp', 'sprucei', 'sp', 'species')
names[names=='sp'] <- 'indet'
names
# [1] "indet" "sprucei" "indet" "species"
与MrFlick的解决方案不同,如果在'sp'
之前或之后有空格或单词,则此方法将无效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.