Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sub() and gsub() have the same results? [duplicate]

Tags:

r

gsub

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"
like image 495
andrew Avatar asked Nov 22 '25 20:11

andrew


1 Answers

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".

like image 177
Ronak Shah Avatar answered Nov 24 '25 10:11

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!