I have the following vector
x = c("AXX", "XAX", "XXA")
I would like to replace all the "A"
to "B"
in x
, but not if "A"
is at the beginning of the string. Desired:
c("AXX", "XBX", "XXB")
Use a negated start anchor in a regular expression:
x <- c("AXX", "XAX", "XXA")
Base R
gsub("(?!^)A", "B", x, perl=TRUE)
##[1] "AXX" "XBX" "XXB"
stringr
library(stringr)
str_replace_all(x, "(?!^)A", "B")
##[1] "AXX" "XBX" "XXB"