0

If I have a matrix say:

> mat1=matrix(1:12, ncol=3)
> mat1
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

What do I do to replicate each column and put it next to the original so it looks like this:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    5    5    9    9    
[2,]    2    2    6    6   10   10
[3,]    3    3    7    7   11   11
[4,]    4    4    8    8   12   12

I'm sure this is really simple but can't see it! Many thanks.

Edward Armstrong
  • 329
  • 2
  • 3
  • 12

2 Answers2

2

Try this:

mat1=matrix(1:12, ncol=3)
mat1[,rep(1:ncol(mat1),each=2)]
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    1    5    5    9    9
## [2,]    2    2    6    6   10   10
## [3,]    3    3    7    7   11   11
## [4,]    4    4    8    8   12   12
bartektartanus
  • 15,284
  • 6
  • 74
  • 102
0

Probably easiest to re-order a simple cbind:

cbind(mat, mat)[,order(rep(1:ncol(mat), times=2))]

or

mat[,rep(1:ncol(mat), each=2)]
Gavin Kelly
  • 2,374
  • 1
  • 10
  • 13