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?
y <- strsplit(x, "")[[1]];
y[pos] <- "*";
paste0(y, collapse = "")
– jtr13paste(replace(unlist(strsplit(x, "")), pos, "*"), collapse = "")
– d.bgsub
– slava-kohut