[R] backslash quirk in paste

Prof J C Nash (U30A) nashjc at uottawa.ca
Sat Dec 6 20:33:30 CET 2014


Thanks. Now why didn't I think of that? However, it underlines that
there is an implicit call to print(), which processes the string rather
than simply dumping it to the screen. That's something to remember (and
I should have!).

Best, JN


On 14-12-06 02:30 PM, Ben Tupper wrote:
> Hi,
> 
> When you call paste without assigning the value it returns to anything it runs through the print command.  So, while your string may contain escapes, using print will not present escapes as you are expecting them.  In this case you could wrap cat() around your paste command.  
> 
>> cat(paste(fname, '\\', lname), "\n")
> John \ Smith 
> 
> See FAQ 7.37 
> 
> http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-does-backslash-behave-strangely-inside-strings_003f
> 
> Cheers,
> Ben
> 
>> sessionInfo()
> R version 3.1.0 (2014-04-10)
> Platform: x86_64-apple-darwin13.1.0 (64-bit)
> 
> locale:
> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
> 
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base     
> 
> loaded via a namespace (and not attached):
> [1] tools_3.1.0
> 
> 
> On Dec 6, 2014, at 2:00 PM, Prof J C Nash (U30A) <nashjc at uottawa.ca> wrote:
> 
>> This is NOT critical. It arose due to a fumble fingers when developing
>> an R example, but slightly intriguing.
>>
>> How could one build a string from substrings with a single backslash (\)
>> as separator. Here's the reproducible example:
>>
>> fname = "John"; lname = "Smith"
>> paste(fname, lname)
>> paste(fname, lname, sep=" / ")
>> # BUT there's a glitch with backslash
>> paste(fname, lname, sep=" \ ") # because of escaping character
>> paste(fname, lname, sep=' \ ')
>> paste(fname, lname, sep=' \\ ') # because of escaping character
>> bslash <- "\\"
>> print(bslash)
>> paste(fname, lname, sep=bslash)
>>
>> Possibly the answer is that R never allows a single backslash in its
>> strings, but I can imagine possible cases where I might want to output
>> such lines, for example, in documenting this.
>>
>> Best, JN
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> 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.
> 
> Ben Tupper
> Bigelow Laboratory for Ocean Sciences
> 60 Bigelow Drive, P.O. Box 380
> East Boothbay, Maine 04544
> http://www.bigelow.org
> 
> 
> 
> 
> 
> 
> 
>



More information about the R-help mailing list