Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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)]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top