假设您要将第二个字符串匹配替换为向量替换中的第二个元素。例如:
x <- "CBCADEFGHI"
pattern <- "(A|D|C)"
replacement <- c("X","Y","Z")
你将如何更换第二种模式匹配,即&#34; C&#34;因为它是第二个被发现的模式,带有相应的替换向量元素&#34; Z&#34;?
期望的输出:
"CBZADEFGHI"
答案 0 :(得分:8)
希望我能正确理解这一点。这是我的想法。
## find the position of the second match
g <- gregexpr(pattern, x)[[1]][2]
## get the individual letter elements out of 'pattern'
s <- scan(text = gsub("[()]", "", pattern), sep = "|", what = "")
## replace the position 'g' in 'x' with the matched element in 'replacement'
substr(x, g, g) <- replacement[match(substr(x, g, g), s)]
## resulting in
x
# [1] "CBZADEFGHI"