[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 20:04:47 CET 2009


Peter Dalgaard wrote:
> 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.

... unless of course, Sean really intended to replace a single slash 
with a SINGLE backslash.

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