x <- c("This is a sentence about axis",
"A second pattern is also listed here")
sub(".*is", "XY", x)
#[1] "XY" "XYted here"
gsub(".*is", "XY", x)
#[1] "XY" "XYted here"
When you are using the pattern ".*is", it matches everything from start of the string to the last "is", which in first sentence is "is" in "axis" and "is" in "listed" in 2nd string. Hence, everything upto that part gets replaced by "XY".
What probably you might be expecting is :
sub("is", "XY", x)
#[1] "ThXY is a sentence about axis" "A second pattern XY also listed here"
gsub("is", "XY", x)
#[1] "ThXY XY a sentence about axXY" "A second pattern XY also lXYted here
As you can see in the sub call only the first "is" is replaced whereas in gsub all of the instances of "is" are replaced with "XY".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With