![](/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.