[R] how to replace a single forward slash with a double backward slash in a string?
David Winsemius
dwinsemius at comcast.net
Sun Dec 13 20:17:17 CET 2009
On Dec 13, 2009, at 1:58 PM, 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.
>
> > 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... ;-)
Thanks. I'm probably not the last, but seeing as this is not my first
effort at this either, let me make an effort toward preventing myself
(and Zhang) from getting it wrong (again).
-- The console display is a potentially misleading representation of
the string object in the sense that it displays any "\" characters as
"\\"?
-- When used in a regular expression, one needs to use FOUR "\"'s to
get one 'internal' "\", the first two "\\" create one escape-char
within the parser then which then applies to the second escape-char
created by the second two "\\"?
(I think I have seen both those facts in print before, but perhaps
typing them will make it stick this time.)
>
> --
> 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
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list