[R] Problem with print() and backslashes.

Henrik Bengtsson hb at maths.lth.se
Tue Nov 30 10:10:58 CET 2004


> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Kevin Brinkmann
> Sent: Tuesday, November 30, 2004 9:43 AM
> To: R-help at stat.math.ethz.ch
> Subject: [R] Problem with print() and backslashes.
> 
> 
> Dear R List
> 
> I have a small problem concerning the output of print().
>
<snip></snip> 
> 
> Consider this: I want to print a backslash with an
> exclamation mark. Here is the output.
> 
> > print( "\!" )
> [1] "!"
> 
> Now I try it differently...
> 
> > print( "\\!" )
> [1] "\\!"
> 
> The output contains two backslashes. Why?

> cat("\\!")
\!

also

> str("\\!")
 chr "\!"


What is important to keep in mind is that the string "\\!" has *two*
characters (when read by R), not three (as on the screen or in your editor);

> nchar("\\!")
[1] 2

The first character is "\\", which needs to be escaped in order for the R
parser to recognize it as '\'. The second is of course '!'. I agree that

> nchar("\!")
[1] 1

might be confusing. The thing is that some characters remain the same
escaped or not, whereas others have certain mappings to non-printable ASCII
codes (0-255).

> identical("\!", "!")
[1] TRUE

and the well known(?) newline character

> identical("\n", "n")
[1] FALSE

Another good example:
> identical("\"", '"')
[1] TRUE

Given a string, print() gives you the escaped version of the string, which
can be useful for debugging, if you want to cut'n'paste and so on. Thus,

> print("Hello world\n!\n")
[1] "Hello world\n!\n"

and

> cat("Hello world\n!\n")
Hello world
!

Hope this helps!

Henrik Bengtsson

> Regards,
> 
> Kevin
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list