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

Erik Iverson eriki at ccbr.umn.edu
Thu Mar 25 20:15:01 CET 2010



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)))
> 
>

Or even a little bit "DRY"er:

pc <- function(...) paste(..., collapse = " ")
rd <- function(n) pc(rep(".", n))
pc(rd(2), "a string", rd(3))



More information about the R-help mailing list