Interleaving elements of two vectors?
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 ------------------------------