1
votes

I would like to replace every 5th character in a single string with *. Here's a MWE:

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

I would like the output to be:

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

string::sub_str() can identify the characters at those positions:

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

It doesn't work to replace them, however, since sub_str() expects the string parameter to be a vector of the same length as the start and end parameters. Not finding that, it recycles string to match the length of start/end and makes one replacement per element:

> 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."

Any ideas on how to get the desired output simply, with or without stringr:sub_str(), but preferably without a for loop?

1
That's not working for me (maybe you're using shortcut notation that I'm not following) but breaking it up works: y <- strsplit(x, "")[[1]]; y[pos] <- "*"; paste0(y, collapse = "")jtr13
paste(replace(unlist(strsplit(x, "")), pos, "*"), collapse = "")d.b
Your approach should be as follows: generate a regex pattern from your positions, then run gsubslava-kohut
I was hoping that stringr would save me from regex for something quite simple like this.jtr13

1 Answers

1
votes
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."