How to convert '
in a string to \'
in R?
Example: from Bob's
to Bob\'s
How to convert '
in a string to \'
in R?
Example: from Bob's
to Bob\'s
> gsub("'", "\\\\'", "foo's bar's")
[1] "foo\\'s bar\\'s"
The results looks like the backslashes are double-escaped, but if you check with nchars() you'll see that it's actually just single backslashes.
I finally figured it out:
gsub("\'", "\\\'", "Bob's")
What confused me was that the backslash isn't displayed.
You have to escape the backslash.
> gsub("'","\\\\'","Bob's") # R prints with the escape embedded
[1] "Bob\\'s"
> cat(gsub("'","\\\\'","Bob's"),"\n") # But it's just a single backslash
Bob\'s