r 替换字符串中第n个出现的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r 替换字符串中第n个出现的值相关的知识,希望对你有一定的参考价值。
str_replace_n <- function(x, pattern, replace, n){
g <- gregexpr(pattern,x)[[1]][n]
output <- paste0(substr(x,1,g-1),replace,substr(x,g+1,nchar(x)))
output
}
str_replace_n("ALLAHABAD","A","U",3)
#[1] "ALLAHUBAD"
str_replace_nth <- function(x, pattern, replacement, n) {
g <- gregexpr(pattern, x)[[1]][n]
s <- scan(text = gsub("[()]", "", pattern),
sep = "|",
what = "")
substr(x, g, g) <- replacement[match(substr(x, g, g), s)]
x
}
str_replace_nth("ALLAHABAD","A","U",2)
#[1] "ALLUHABAD"
以上是关于r 替换字符串中第n个出现的值的主要内容,如果未能解决你的问题,请参考以下文章