Add number in the string after each letter
Another option:
gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "\\1\\21", strings, perl = T)
Output:
[1] "A1" "A3B1C3" "A2B1C1"
Or if you only have capitals, just:
gsub("([A-Z])(?=[A-Z])|([A-Z])$", "\\1\\21", strings, perl = T)
Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1
in this case.
Find all (uppercase) letters ([A-Z]
) that is not followed by a number and replace it with that string + 1
:
gsub("([A-Z])(?![0-9])", "\\11", strings, perl = TRUE)
# [1] "A1" "A3B1C3" "A2B1C1"