可以通过使用R中的矩阵函数来创建矩阵,如果我们想通过复制向量来创建矩阵,那么我们只需要关注复制。例如,如果我们有一个向量V,并且希望通过复制V两次来创建矩阵,则可以将矩阵创建为matrix(replicate(2,V),nrow = 2)。
V1<-1:5 matrix(replicate(2,V1),nrow=5)
输出结果
[,1] [,2] [1,] 1 1 [2,] 2 2 [3,] 3 3 [4,] 4 4 [5,] 5 5
matrix(replicate(5,V1),nrow=5)
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 2 2 2 2 2 [3,] 3 3 3 3 3 [4,] 4 4 4 4 4 [5,] 5 5 5 5 5
matrix(replicate(10,V1),nrow=5)
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 1 1 1 1 1 1 1 [2,] 2 2 2 2 2 2 2 2 2 2 [3,] 3 3 3 3 3 3 3 3 3 3 [4,] 4 4 4 4 4 4 4 4 4 4 [5,] 5 5 5 5 5 5 5 5 5 5
matrix(replicate(9,V1),nrow=5)
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 1 1 1 1 1 1 1 1 1 [2,] 2 2 2 2 2 2 2 2 2 [3,] 3 3 3 3 3 3 3 3 3 [4,] 4 4 4 4 4 4 4 4 4 [5,] 5 5 5 5 5 5 5 5 5
V2<-rpois(10,5) V2
输出结果
[1] 1 4 2 6 7 2 4 4 2 8
matrix(replicate(2,V2),nrow=10)
输出结果
[,1] [,2] [1,] 1 1 [2,] 4 4 [3,] 2 2 [4,] 6 6 [5,] 7 7 [6,] 2 2 [7,] 4 4 [8,] 4 4 [9,] 2 2 [10,] 8 8
matrix(replicate(5,V2),nrow=10)
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 4 4 4 4 4 [3,] 2 2 2 2 2 [4,] 6 6 6 6 6 [5,] 7 7 7 7 7 [6,] 2 2 2 2 2 [7,] 4 4 4 4 4 [8,] 4 4 4 4 4 [9,] 2 2 2 2 2 [10,] 8 8 8 8 8
matrix(replicate(10,V2),nrow=10)
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 1 1 1 1 1 1 1 [2,] 4 4 4 4 4 4 4 4 4 4 [3,] 2 2 2 2 2 2 2 2 2 2 [4,] 6 6 6 6 6 6 6 6 6 6 [5,] 7 7 7 7 7 7 7 7 7 7 [6,] 2 2 2 2 2 2 2 2 2 2 [7,] 4 4 4 4 4 4 4 4 4 4 [8,] 4 4 4 4 4 4 4 4 4 4 [9,] 2 2 2 2 2 2 2 2 2 2 [10,] 8 8 8 8 8 8 8 8 8 8
V3<-sample(0:9,10,replace=TRUE) V3
输出结果
[1] 1 8 8 5 9 7 0 7 1 8 matrix(replicate(5,V3),nrow=10)
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 8 8 8 8 8 [3,] 8 8 8 8 8 [4,] 5 5 5 5 5 [5,] 9 9 9 9 9 [6,] 7 7 7 7 7 [7,] 0 0 0 0 0 [8,] 7 7 7 7 7 [9,] 1 1 1 1 1 [10,] 8 8 8 8 8
matrix(replicate(3,V3),nrow=10)
输出结果
[,1] [,2] [,3] [1,] 1 1 1 [2,] 8 8 8 [3,] 8 8 8 [4,] 5 5 5 [5,] 9 9 9 [6,] 7 7 7 [7,] 0 0 0 [8,] 7 7 7 [9,] 1 1 1 [10,] 8 8 8
matrix(replicate(12,V3),nrow=10)
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,] 1 1 1 1 1 1 1 1 1 1 1 1 [2,] 8 8 8 8 8 8 8 8 8 8 8 8 [3,] 8 8 8 8 8 8 8 8 8 8 8 8 [4,] 5 5 5 5 5 5 5 5 5 5 5 5 [5,] 9 9 9 9 9 9 9 9 9 9 9 9 [6,] 7 7 7 7 7 7 7 7 7 7 7 7 [7,] 0 0 0 0 0 0 0 0 0 0 0 0 [8,] 7 7 7 7 7 7 7 7 7 7 7 7 [9,] 1 1 1 1 1 1 1 1 1 1 1 1 [10,] 8 8 8 8 8 8 8 8 8 8 8 8