rmatrix

Replicate matrix


Problem

Say I have this matrix in R:

(x <- matrix(1:6, ncol = 3, byrow = TRUE))
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

which I want to combine by rows multiple times. Here's an example using rbind()

rbind(x, x)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    1    2    3
[4,]    4    5    6

The problem is that I want to do this an indefinite number of times inside a function, and I'm trying to avoid just looping around x making copies of it.

What I've tried so far

I've tried several operations involving replicate(), array(), matrix(), *apply(), and the closest I get to what I want is this (for two reps):

replicate(2, rbind(x))
, , 1

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

, , 2

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

If I try to collapse this into a matrix, the elements get mixed up because of how the array sequence is stored:

as.vector(replicate(2, rbind(x)))
[1] 1 4 2 5 3 6 1 4 2 5 3 6

A clumsy solution

So far, the only way I got what I wanted is by abusing t():

t(array(t(x), dim = c(ncol(x), nrow(x) * 2)))
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    1    2    3
[4,]    4    5    6

I bet there's a cleaner way to achieve this, but after a couple of hours I'm stumped. Any help?

Related questions

Here are some related questions with solutions I've tried without success:


Solution

  • You could try

    > do.call(rbind, replicate(2, x, FALSE))
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    1    2    3
    [4,]    4    5    6
    
    > kronecker(rep(1, 2), x)
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    1    2    3
    [4,]    4    5    6
    
    > matrix(aperm(replicate(2, x), c(1, 3, 2)), ncol = ncol(x))
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    1    2    3
    [4,]    4    5    6
    
    > matrix(rep(t(x), 2), ncol = ncol(x), byrow = TRUE)
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    1    2    3
    [4,]    4    5    6