[R] Interlacing two vectors

Richard A. O'Keefe ok at cs.otago.ac.nz
Thu Aug 21 05:34:41 CEST 2003


Murray Jorgensen <maj at stats.waikato.ac.nz> wrote:
	I want to interlace two vectors.

How, precisely, do you want to do this?

Here are two vectors x and y of the same length:
    x <- c(1,2,3)
    y <- c(4,5,6)
The simplest way I can think of to interleave them is
    as.vector(rbind(x,y))
=>  1 4 2 5 3 6
This will work for any number of vectors:    
    z <- c(7,8,9)
    as.vector(rbind(x,y,z))
=>  1 4 7 2 5 8 3 6 9

Another approach is this:
    r <- 1:(2*length(x))
    i <- r%%2
    r[i == 1] <- x
    r[i == 0] <- y
    r
=>  1 4 2 5 3 6
That generalises too:
    r <- 1:(3*length(x))
    i <- r%%3
    r[i == 1] <- x
    r[i == 2] <- y
    r[i == 0] <- z
    r
=>  1 4 7 2 5 8 3 6 9

I prefer as.vector(rbind(x,y,...))); as it uses fewer R-level operations
and should if anything turn over less space, I'd expect it to be faster
as well as simpler.




More information about the R-help mailing list