Skip to content

Problem with print() and backslashes.

4 messages · Kevin Brinkmann, Peter Dalgaard, Brian Ripley +1 more

#
Dear R List

I have a small problem concerning the output of print().

My version:
_
platform i386-portbld-freebsd5.2
arch     i386
os       freebsd5.2
system   i386, freebsd5.2
status
major    1
minor    9.0
year     2004
month    04
day      12
language R

Consider this: I want to print a backslash with an exclamation mark. Here
is the output.
[1] "!"

Now I try it differently...
[1] "\\!"

The output contains two backslashes. Why?

Regards,

Kevin
#
Kevin Brinkmann <kbrinkm at ump.gwdg.de> writes:
(Didn't we do that one only yesterday?)

The answer is: For the same reason that you need them on input. R
likes to line things up in columns when printing vectors so cannot
just print special characters like newline, carriage return, etc.
Instead it represents them as \n, \r just like on input. To
distinguish from backslash-followed-by-n the backslash is itself
escaped with a backslash. Use cat() to output a string as raw
characters.
#
On Tue, 30 Nov 2004, Kevin Brinkmann wrote:

            
Because it is documented to escape backslashes: use cat() if that is not 
what you want.
#
<snip></snip>
\!

also
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);
[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
[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).
[1] TRUE

and the well known(?) newline character
[1] FALSE

Another good example:
[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,
[1] "Hello world\n!\n"

and
Hello world
!

Hope this helps!

Henrik Bengtsson