如果我有一个矩阵说:
> 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
如何复制每一列并将其放在原始列旁边,这样看起来像这样:
[,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
我确信这很简单但看不到它!非常感谢。
答案 0 :(得分:2)
试试这个:
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
答案 1 :(得分:0)
可能最容易重新订购一个简单的cbind:
cbind(mat, mat)[,order(rep(1:ncol(mat), times=2))]
或
mat[,rep(1:ncol(mat), each=2)]