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

Sarah Goslee sarah.goslee at gmail.com
Thu Mar 25 20:35:19 CET 2010

On Thu, Mar 25, 2010 at 3:19 PM, Ted Harding
<Ted.Harding at manchester.ac.uk> wrote:

> 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"!

Yes, because you are pasting
a vector of length 2
a vector of length 1
a vector of length 3

R has no idea what you mean. paste() by default recycles
elements to match the longest vector. Paste tje first element
of the first vector, the first element of the second, then the
first element of the third into the first result string.
Paste the second element of the first vector, the second of the
second... etc.
With elements recycled as necessary.

Careful use of c() gives you the "expected" results:

> v1 <- c("a", "a")
> v2 <- c("b")
> v3 <- c("c", "c", "c")
>
> paste(v1, v2, v3)
[1] "a b c" "a b c" "a b c"
> paste(v1, v2, v3, collapse=" ")
[1] "a b c a b c a b c"
>
>
> paste(c(v1, v2, v3))
[1] "a" "a" "b" "c" "c" "c"
>
> paste(c(v1, v2, v3), collapse=" ")
[1] "a a b c c c"
>
> paste(c(v1, v2), v3)
[1] "a c" "a c" "b c"

Sarah

--
Sarah Goslee
http://www.functionaldiversity.org