raw = c("MOUNTAIN VIEW","MOUNTAIN")
x = gsub("MOUNTAIN", "MOUNTAIN VIEW", raw, ignore.case = TRUE)
Current output: "MOUNTAIN VIEW VIEW" "MOUNTAIN VIEW"
Desired output: "MOUNTAIN VIEW" "MOUNTAIN VIEW"
我只想将原始数据MOUNTAIN
中的第二个条目替换为MOUNTAIN VIEW
。原始数据中的第一个条目已经正确。但是当我执行gsub
时,它会将MOUNTAIN
的出现替换为MOUNTAIN VIEW
。任何人都可以帮我找到解决方法吗?
我尝试了\\b
,但它没有用,我理解为什么。还有什么我能做的吗?
答案 0 :(得分:2)
此处使用anchors来匹配整个字符串:
sub('^MOUNTAIN$', 'MOUNTAIN VIEW', raw, ignore.case = TRUE)
# [1] "MOUNTAIN VIEW" "MOUNTAIN VIEW"
如果您愿意,您还可以使用捕获组并在替换呼叫中反向引用它:
sub('^(MOUNTAIN)$', '\\1 VIEW', raw, ignore.case = TRUE)
答案 1 :(得分:0)
使用agrep
- 返回矢量索引,因此您可以使用subscripts
轻松指定值:
raw[agrep("MOUNTAIN", raw)] <- "MOUNTAIN VIEW"
raw
[1] "MOUNTAIN VIEW" "MOUNTAIN VIEW"