[R] Interleaving elements of two vectors?

(Ted Harding) Ted.Harding at manchester.ac.uk
Thu Mar 25 23:00:42 CET 2010


On 25-Mar-10 21:10:17, Jeff Brown wrote:
> I just had to solve this problem for myself, after not having
> luck with the code posted above. I'm posting in case others
> need a completely general function.
> 
> riffle <- function (a,b) {
>       # Interleave a & b, starting with a, without repeating.
>       x <- NULL;              count = 1;
>       for (i in 1:max(length(a), length(b))) {
>               if (i <= length(a)) {
>                       x[count] <- a[i];
>                       count = count+1;
>               };
>               if (i <= length(b)) {
>                       x[count] <- b[i];
>                       count = count+1;
>               }
>       };
>       x
> };
> riffle( 1:10, 50:55 )

The following avoids the 'for' loop, though I'd like to simplify
the conditionals:

  riffle2 <- function(x,y){
    m0 <- length(x); n0 <- length(y)
    m  <- min(m0,n0); n <- max(m0,n0)
    z  <- numeric(m+n)
    if(m0==n0){ z[(-1+2*(1:m))] <- x ; z[2*(1:m)] <- y } else
    if(m0<n0){
      z[(-1+2*(1:m))] <- x
      z[2*(1:m)]      <- y[1:m]
      z[(2*m+1):(m+n)]    <- y[(m+1):n]
    } else {
      z[(2*(1:m))]    <- y
      z[-1+2*(1:m)]   <- x[1:m]
      z[(2*m+1):(m+n)]    <- x[(m+1):n]
    }
    z
  }

  riffle2((1:10),(50:55))
  # [1]  1 50  2 51  3 52  4 53  5 54  6 55  7  8  9 10

  riffle2((50:55),(1:10))
  # [1] 50  1 51  2 52  3 53  4 54  5 55  6  7  8  9 10

  riffle2((1:7),(8:14))
  # [1]  1  8  2  9  3 10  4 11  5 12  6 13  7 14

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:00:38
------------------------------ XFMail ------------------------------



More information about the R-help mailing list