I would like to insert an extra character (or a new string) at a specific location in a string. For example, I want to insert d at the fourth location in abcefg to get abcdefg.
Now I am using:
old <- "abcefg"
n <- 4
paste(substr(old, 1, n-1), "d", substr(old, n, nchar(old)), sep = "")
I could write a one-line simple function for this task, but I am just curious if there is an existing function for that.
You can do this with regular expressions and
gsub.If you want to do this dynamically, you can create the expressions using
paste:as per DWin’s comment,you may want this to be more general.
This way any three characters will match rather than only lower case. DWin also suggests using
subinstead ofgsub. This way you don’t have to worry about the^as much sincesubwill only match the first instance. But I like to be explicit in regular expressions and only move to more general ones as I understand them and find a need for more generality.as Greg Snow noted, you can use another form of regular expression that looks behind matches:
and could also build my dynamic
gsubabove usingsprintfrather thanpaste0:or for his
subregular expression: