[R] Interleaving elements of two vectors?
(Ted Harding)
Ted.Harding at manchester.ac.uk
Thu Mar 25 23:47:18 CET 2010
On 25-Mar-10 22:17:23, Rolf Turner wrote:
>
> I think that
>
> riffle <- function (a,b) {
> n <- min(length(a),length(b))
> p1 <- as.vector(rbind(a[1:n],b[1:n]))
> p2 <- c(a[-(1:n)],b[-(1:n)])
> c(p1,p2)
> }
>
> does the trick, and is pretty simple ....
> cheers,
> Rolf Turner
The "rbind" step is already quite neat.
But the "c(a[-(1:n)],b[-(1:n)])" is the real magic!
The "trick" of course is that even if length(b) < n,
b[-(1:n)] still makes sense, returning integer(0) which
will not extend anything it is c()'d with.
Nice.
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 25-Mar-10 Time: 22:47:15
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list