Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate matrix

Tags:

r

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:

  • Replicate Matrix in R
  • how to bind the same vector multiple times?
  • under what circumstances does R recycle?
like image 997
Waldir Leoncio Avatar asked Aug 10 '26 23:08

Waldir Leoncio


1 Answers

You could try

  • replicate with option simplify = FALSE, and use do.call(rbind,...) in turn
> 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
  • Using kronecker
> kronecker(rep(1, 2), x)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    1    2    3
[4,]    4    5    6
  • Using aperm
> 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
  • Using rep
> 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
like image 152
ThomasIsCoding Avatar answered Aug 12 '26 19:08

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!