tags:

views:

93

answers:

3
+2  Q: 

Replacing ' by \'

How to convert ' in a string to \' in R?

Example: from Bob's to Bob\'s

+2  A: 
> 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.

Daniel Dickison
A: 

I finally figured it out:

gsub("\'", "\\\'", "Bob's")

What confused me was that the backslash isn't displayed.

echino
+5  A: 

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 
Joshua Ulrich