[R] c(), or cat(), or paste(), all cause unwanted reordering

(Ted Harding) Ted.Harding at manchester.ac.uk
Thu Mar 25 20:19:12 CET 2010


On 25-Mar-10 19:07:23, Erik Iverson wrote:
> Hello,
> 
> Jeff Brown wrote:
>> I would expect the following:
>> 
>> paste(
>>      as.character( cat( rep( ".", 2 ) ) ),   
>>      "a string",
>>      as.character( cat( rep( ".", 3 ) ) )
>> );
>> 
>> to yield this string: ". . a string . . .", but instead it yields
>> this:
>> 
>>> . .. . .[1] " a string "
>> 
> cat is writing its output to the console, not creating an object
> like you want.  notice the second cat will return (and write to
> the console) before paste.
> 
> You need the collapse argument to paste, forget about cat for this.
> Try:
> 
> pc <- function(...) paste(..., collapse = " ")
> rd <- function(n) rep(".", n)
> pc(pc(rd(2)), "a string", pc(rd(3)))
> 
> Probably many other ways.
> --Erik

One needs to be very circumspect with this sort of thing! For instance,
experimenting with simplifications of Jeff's expression:

  paste(
          rep( ".", 2 ),                          
          "a string",
          rep( ".", 3 )
  )

  # [1] ". a string ." ". a string ." ". a string ."

Here, it seems to be recycling the length-2 and length-3 vectors
rep( ".", 2 ) and rep( ".", 3 ) around the length-1 vector "a string"!

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 25-Mar-10                                       Time: 19:19:08
------------------------------ XFMail ------------------------------



More information about the R-help mailing list