2

There is a function in Mathematica called "Riffle" that can be used for inserting columns of a matrix between columns of another matrix.For example, for m1 and m2 matrices like these:

m1= 1   1   1
    1   1   1
    1   1   1

m2=2    2   2
   2    2   2
   2    2   2

it creates

1   2   1   2   1   2
1   2   1   2   1   2
1   2   1   2   1   2

is there any equivalent function in R for doing this?

Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
Amin
  • 368
  • 1
  • 5
  • 14
  • 3
    Are you looking for the specific behavior you describe in this question, or something that behaves more like the actual `Riffle` function? If it's the former, something as straightforward as `cbind(m1, m2)[, order(sequence(c(ncol(m1), ncol(m2))))]` should work. – A5C1D2H2I1M1N2O1R2T1 Jan 25 '14 at 07:16
  • 1
    Something to play around with: https://gist.github.com/mrdwab/8618900 – A5C1D2H2I1M1N2O1R2T1 Jan 25 '14 at 16:27

2 Answers2

4

Assuming that you matrices have equal dimensions, you might use this little trick

m <- rbind(m1, m2)
dim(m) <- rev(dim(m))

m
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    1    2    1    2
[2,]    1    2    1    2    1    2
[3,]    1    2    1    2    1    2

Another option would be to use the interleave function from the gdata package. The function interleaves rows not columns, so you need to transpose your matrices back and forth.

m <- t(interleave(t(m1), t(m2)))

m
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    1    2    1    2
[2,]    1    2    1    2    1    2
[3,]    1    2    1    2    1    2
Mark Heckmann
  • 10,943
  • 4
  • 56
  • 88
3

Don't know if it already exists (never seen it), but it is not to difficult to write:

riffle <- function(a,b) {
  if (!all(dim(a) == dim(b))) stop("dimensions do not match")
  array(rbind(a, b), dim=c(dim(a)[1], dim(a)[1]+dim(b)[1]))
}
Jan van der Laan
  • 8,005
  • 1
  • 20
  • 35