[R] Using GSUB to obtain a printing "\"

Bhushan, Vipul vipul.bhushan at geodecapital.com
Thu May 5 23:47:35 CEST 2011


Hello. I'd like to be able to print variable strings which contain "\" as-is, without interpreting (for example) "abcde\nuvxyz" as having an embedded newline (or whatever other escaped instruction). 

To do this, I've tried gsub, and here's some of my output (I've tried all kinds of variations to the arguments): 

> message(gsub("[\\]","\\\\","dsff\nfsd"))
dsff
fsd

but I would like to see:
dsff\nfsd  
(which is the output of message("dsff\\nfsd") )

I don't know why gsub doesn't accomplish this substitution. How can I replace (for example), a "\" with "\\"? Any suggestions would be greatly appreciated. (I know I can use another language, or use inelegant brute force by writing a new routine which cycles through each possible character that could follow the single "\".) Watching the gsub echo at the R prompt shows that it is gsub (and not message) not behaving as I expected. 


Other information which the posting guidelines say might help:
> sessionInfo()
R version 2.13.0 (2011-04-13)
Platform: x86_64-apple-darwin10.7.0/x86_64 (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] Rd2roxygen_0.1-8 roxygen_0.1-2    digest_0.4.2    

loaded via a namespace (and not attached):
[1] tools_2.13.0
> Sys.getlocale()
[1] "C"

Thanks very much!



More information about the R-help mailing list