向量化使用str_sub替换字符串中的多个固定位置字符

时间:2019-09-25 15:25:27

标签: r stringr

我想用*替换单个字符串中的第5个字符。这是MWE:

x <- "Mary had a little lamb."
pos <- c(5, 10, 15, 20)

我希望输出为:

[1] "Mary*had * lit*le l*amb."

string::sub_str()可以识别这些位置的字符:

> stringr::str_sub(string = x, start = pos, end = pos)
[1] " " "a" "t" "a"

无法替换它们,因为sub_str()期望 string 参数是与 start 长度相同的向量,并且 end 参数。找不到它,它回收 string 以匹配 start / end 的长度,并对每个元素进行一次替换:

> stringr::str_sub(string = x, start = pos, end = pos) <- "*"
> x
[1] "Mary*had a little lamb." "Mary had * little lamb."
[3] "Mary had a lit*le lamb." "Mary had a little l*mb."

有没有关于如何简单地获得所需输出的想法,有无stringr:sub_str(),但最好没有for循环?

1 个答案:

答案 0 :(得分:1)

foo = function(x, pos, rep = "*"){
    tmp = x
    for (i in pos) {
        substr(tmp, i, i) = rep
    }
    tmp
}
foo(x, pos)
#[1] "Mary*had * lit*le l*mb."