Skip to content

puzzled by cat() behaviour when argument '...' is a vector (and argument 'sep' contains "\n")

1 message · Steven McKinney

#
It appears to me that the elements of sep are just used as separators 
_between_ each of the objects comprising '...' handed to cat.  

If N objects are handed to cat, cat requires N-1 separator strings.
The default separator string is " " (space character).

Hence for
cat(rep("x",3), sep = ".")
two periods are needed to separate the three input objects
x.x.x
as expected.

For cat(rep("x",3),sep = c(".","\n",".")), the first separator
is a period, the second is a newline, and the third is not needed.
x.x
x
as expected.  The line feed inserted is expected, it is the
second element of the sep vector, so should appear between
the second and third objects, as it does.  The third element 
of sep is not needed, so is ignored.

Another example:
a1b2c3d4e5f6g7h8i9j
k1l2m3n4o5p6q7r8s9t
u1v2w3x4y5z
Again, as expected.

Slightly more complex
[1] "[1]"  "[2]"  "[3]"  "[4]"  "[5]"  "[6]"  "[7]"  "[8]"  "[9]"  "[\n]"
a[1]b[2]c[3]d[4]e[5]f[6]g[7]h[8]i[9]j[
]k[1]l[2]m[3]n[4]o[5]p[6]q[7]r[8]s[9]t[
]u[1]v[2]w[3]x[4]y[5]z
again, as expected.

I haven't delved into the source to see where the final line feed
is being generated (as I see the next R prompt on a new line) so
I can't comment on whether anything is appended to the end of the
output string generated by cat().  The documentation says no line
feed is appended unless argument 'fill' is TRUE or numeric.
How about this:

sep    a character vector of strings to insert between each object.  If 
       there are too few elements in sep to separate all the objects, 
       the elements of sep are recycled.  Unused elements of sep are ignored.


then in Details:

Details

cat is useful for producing output in user-defined functions. It
converts its arguments to character vectors, concatenates them to a
single character vector, inserts the given sep= string(s) between each
element and then outputs them.
Steven McKinney

Statistician
Molecular Oncology and Breast Cancer Program
British Columbia Cancer Research Centre

email: smckinney +at+ bccrc +dot+ ca

tel: 604-675-8000 x7561

BCCRC
Molecular Oncology
675 West 10th Ave, Floor 4
Vancouver B.C. 
V5Z 1L3
Canada