[R] How to get the string '\'?

David Winsemius dwinsemius at comcast.net
Mon Nov 16 01:05:36 CET 2009


On Nov 15, 2009, at 6:35 PM, Peng Yu wrote:

> My question was from replacing a pattern by '\\'. How to replace '/'
> in string by '\'?
>
> string='abc/efg'
> gsub('/','\\',string)

No,  that was most definitely _not_ your posed question. If you want  
now to change your question and supply a reproducible example, that's  
fine, just don't claim that your mind should have been read more  
properly that it was, .... please.

The problem with your _second_ question is that the printed  
representation of "\" is a problem because of its special use as an  
escape symbol. So sometimes it needs to be displayed as "\\". What  
gets written to the screen may be different that the internal  
representation. Look at the results of:
 > string='abc/efg'
 > cat(gsub('/','\\\\',string), file="test.txt")

You should see:
abc\efg

...although at the screen you would see:

 > string='abc/efg'
 > gsub('/','\\\\',string)
[1] "abc\\efg"

The first "\" escapes second "\" which in turn allows whatever follows  
to be interpreted as "escaped", while the third "\" escapes the 4th  
"\" so that it can be examined by the R interpreter as a real "\".


-- 
David.
>
> On Sun, Nov 15, 2009 at 5:07 PM, David Winsemius <dwinsemius at comcast.net 
> > wrote:
>> ?cat
>>
>>> cat("\\")
>> \
>>
>>
>> On Nov 15, 2009, at 5:30 PM, Peng Yu wrote:
>>
>>> I can not get the string '\'. Could somebody let me know how to  
>>> get it?
>>>
>>>> print('\')
>>>
>>> +
>>> +
>>>>
>>>> print('\\')
>>>
>>> [1] "\\"
>>>
>>> ______________________________________________
>>> R-help at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>> PLEASE do read the posting guide
>>> http://www.R-project.org/posting-guide.html
>>> and provide commented, minimal, self-contained, reproducible code.
>>
>> David Winsemius, MD
>> Heritage Laboratories
>> West Hartford, CT
>>
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list