给定矩阵
a <- matrix(c(15,2,11,16,7,12,1,8,3), nrow=3, ncol=3, byrow=T)
我想对矩阵的三个副本进行行绑定,但在每个副本中,除了一个行之外的所有行都应该具有零值。期望的结果:
15 2 11
0 0 0
0 0 0
0 0 0
16 7 12
0 0 0
0 0 0
0 0 0
1 8 3
我可以通过rbind(a[1,],0,0,0,a[2,],0,0,0,a[3,])
执行此操作,但处理大型矩阵时有更好的方法吗?
答案 0 :(得分:2)
matrix(t(cbind(a,matrix(0,3,9))),ncol=3,byrow=T)[1:9,]
[,1] [,2] [,3]
[1,] 15 2 11
[2,] 0 0 0
[3,] 0 0 0
[4,] 0 0 0
[5,] 16 7 12
[6,] 0 0 0
[7,] 0 0 0
[8,] 0 0 0
[9,] 1 8 3
答案 1 :(得分:1)
这个怎么样:
apply(a, 2, function(r) rbind(r, matrix(rep(0,9), nrow=3)))[1:9, ]
[,1] [,2] [,3] [1,] 15 2 11 [2,] 0 0 0 [3,] 0 0 0 [4,] 0 0 0 [5,] 16 7 12 [6,] 0 0 0 [7,] 0 0 0 [8,] 0 0 0 [9,] 1 8 3