[R] escaping backslash in a string

Gabor Grothendieck ggrothendieck at myway.com
Mon Nov 29 21:47:50 CET 2004


Dan Lipsitt <danlipsitt <at> gmail.com> writes:

: 
: I have it working now, I think. Since it's going into a regular
: expression, I have to escape each of the escape characters, resulting
: in four backslashes altogether:
: 
: > sub("[.]", "x", "a.b")
: [1] "axb"
: > sub("[.]", "\.", "a.b")
: [1] "a.b"
: > sub("[.]", "\\.", "a.b")
: [1] "a.b"
: > sub("[.]", "\\\.", "a.b")
: [1] "a.b"
: > sub("[.]", "\\\\.", "a.b")
: [1] "a\\.b"
: > cat(sub("[.]", "\\\\.", "a.b"))
: a\.b>
: 
: or
: 
: > cat(sub("\\.", "\\\\.", "a.b"))
: a\.b> 
: 

You can use \134 in place of the double backslash 
if that makes more sense to you.  

Another possibility is to create a variable 
   backslash <- "\\" 
and paste together each string in terms of that variable.

Also its sometimes helpful to use nchar(s) on string s
just to check how many characters it has.




More information about the R-help mailing list