R with gsub() instead ' of \'

I want let a string like "ab'" become "ab\'"

I have tried following code

aa="ab'"
aa<-gsub("'","\\'",aa)    

show ab'

aa="ab'"
aa<-gsub("'","\\\'",aa)

show ab'

aa="ab'"
aa<-gsub("'","\\\\'",aa)

show ab\\'

I don't know how to fixed it please give me some suggest

2 answers

  • answered 2018-07-11 05:26 Tim Biegeleisen

    In the case of the following code:

    aa <- "ab'"
    aa <- gsub("'", "\\\\'", aa)
    

    In fact you are replacing a single quote with a single literal backslash. The output you see ab\\' I believe just shows an extra backslash to let you know that it is not an escape character.

    Consider the following extension of your code:

    gsub("\\\\", "A", gsub("'","\\\\'",aa))
    [1] "abA'"
    

    We can clearly see that there is only a single A in the replacement, implying that there was only a single backslash to be replaced.

  • answered 2018-07-11 05:46 swiftg

    Even though on the terminal, you sometimes see "\\" it is actually just "\".

    Print the result using writeLines() to see the actual string:

    > original_string = "ab'"
    > new_string = gsub("'","\\\\",original_string)
    > writeLines(new_string)
    ab\
    

    Bonus funny: https://xkcd.com/1638/