gsub does this because the string "dsff\nfsd"
does not contain a backslash - the 5th character
is a newline. The deparsed representation (used
for printing the string) of a newline is "\n" but
the string itself has not backslash.
You can feed the output of deparse into message (or
cat) so they show the backslash-n characters, but
you then have to remove the enclosing quotes that
deparse adds.
> x<-"dsff\nfs\rd\1"
> x
[1] "dsff\nfs\rd\001"
> message("x is ", deparse(x))
x is "dsff\nfs\rd\001"
> message("x is ", gsub("^\"|\"$",
"", deparse(x)))
x is dsff\nfs\rd\001
> cat("x is", gsub("^\"|\"$", "",
deparse(x)), "\n")
x is dsff\nfs\rd\001
> cat(x) # this is with Windows Rgui.exe
dsff
fs
d>
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Bhushan, Vipul
> Sent: Thursday, May 05, 2011 2:48 PM
> To: r-help at r-project.org
> Subject: [R] Using GSUB to obtain a printing "\"
>
> 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!
>
> ______________________________________________
> 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.
>