[R] how to replace a single forward slash with a double backward slash in a string?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sun Dec 13 19:58:12 CET 2009


David Winsemius wrote:
> 
> On Dec 13, 2009, at 1:00 PM, Sean Zhang wrote:
> 
>> Dear R-helpers.
>>
>> Can someone kindly tell me how to replace a single forward slash with 
>> double
>> backward slash in a string?
>>
>> i.e.,  from  "a/b" to "a\\b"
> 
>  > sub("/", "\\\\","a/b")
>  #the backslashes need to be doubled because they are the escape character.
> [1] "a\\b"

Bzzzt. Wrong answer.

 > nchar(sub("/", "\\\\","a/b") )
[1] 3
 > cat(sub("/", "\\\\","a/b"),"\n")
a\b

 > nchar(sub("/", "\\\\\\\\","a/b") )
[1] 4
 > sub("/", "\\\\\\\\","a/b")
[1] "a\\\\b"
 > cat(sub("/", "\\\\\\\\","a/b"),"\n")
a\\b

You are not the first... ;-)

-- 
    O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list