首先我们需要了解的是,对角元素仅在具有方矩阵的情况下才有用,否则设置对角元素将毫无意义,这几乎是所有数学家都知道的,但是有些新生可能会感到困惑,因为我们可以在对角元素中创建对角元素。非正方形矩阵,不应称为对角线。在R中,我们可以使用diag函数将矩阵的对角元素设置为缺失值/ NA。
> M1<-matrix(1:16,nrow=4) > M1
输出结果
[,1] [,2] [,3] [,4] [1,] 1 5 9 13 [2,] 2 6 10 14 [3,] 3 7 11 15 [4,] 4 8 12 16
> diag(M1)<-NA > M1
输出结果
[,1] [,2] [,3] [,4] [1,] NA 5 9 13 [2,] 2 NA 10 14 [3,] 3 7 NA 15 [4,] 4 8 12 NA
> M2<-matrix(rpois(100,10),nrow=10) > M2
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 13 18 9 5 15 7 14 7 9 14 [2,] 11 10 12 6 11 13 11 12 6 11 [3,] 12 13 6 6 11 18 9 12 9 6 [4,] 13 14 11 17 17 6 5 10 8 11 [5,] 10 9 15 11 10 14 6 5 5 15 [6,] 8 15 6 10 8 8 10 7 11 7 [7,] 10 12 8 9 12 15 19 9 10 15 [8,] 15 9 4 13 4 13 10 9 11 11 [9,] 7 6 11 12 3 8 12 8 8 11 [10,] 12 13 13 9 11 11 6 6 7 10
> diag(M2)<-NA > M2
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] NA 18 9 5 15 7 14 7 9 14 [2,] 11 NA 12 6 11 13 11 12 6 11 [3,] 12 13 NA 6 11 18 9 12 9 6 [4,] 13 14 11 NA 17 6 5 10 8 11 [5,] 10 9 15 11 NA 14 6 5 5 15 [6,] 8 15 6 10 8 NA 10 7 11 7 [7,] 10 12 8 9 12 15 NA 9 10 15 [8,] 15 9 4 13 4 13 10 NA 11 11 [9,] 7 6 11 12 3 8 12 8 NA 11 [10,] 12 13 13 9 11 11 6 6 7 NA
> M3<-matrix(rpois(25,3),nrow=5) > M3
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] 2 3 4 2 4 [2,] 2 2 3 5 3 [3,] 3 7 6 1 5 [4,] 1 1 4 1 4 [5,] 1 2 0 1 5
> diag(M3)<-NA > M3
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] NA 3 4 2 4 [2,] 2 NA 3 5 3 [3,] 3 7 NA 1 5 [4,] 1 1 4 NA 4 [5,] 1 2 0 1 NA
> M4<-matrix(rnorm(36,5,2.5),nrow=6) > M4
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 7.449650 2.977026 3.631003 1.588073 6.4641515 4.9833353 [2,] 4.326318 4.327728 6.790520 2.367960 0.9577471 5.4084005 [3,] 3.143312 6.766010 5.364526 2.544719 7.9256179 -0.8116725 [4,] 5.983452 5.340530 2.530320 6.830628 4.0030207 7.1645111 [5,] 4.073458 1.795408 -2.391053 6.320859 4.5389839 1.0296674 [6,] 3.739790 6.036844 6.171213 6.901320 5.5595449 4.9644731
> diag(M4)<-NA > M4
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [1,] NA 2.977026 3.631003 1.588073 6.4641515 4.9833353 [2,] 4.326318 NA 6.790520 2.367960 0.9577471 5.4084005 [3,] 3.143312 6.766010 NA 2.544719 7.9256179 -0.8116725 [4,] 5.983452 5.340530 2.530320 NA 4.0030207 7.1645111 [5,] 4.073458 1.795408 -2.391053 6.320859 NA 1.0296674 [6,] 3.739790 6.036844 6.171213 6.901320 5.5595449 NA
> M5<-matrix(runif(25,2,5),nrow=5) > M5
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] 2.753600 3.017767 2.923270 2.532730 3.425423 [2,] 2.742611 2.398763 4.906797 4.273442 3.416288 [3,] 2.744358 4.227648 3.690739 3.508798 3.423980 [4,] 3.124375 2.363392 3.336010 4.770364 3.294046 [5,] 3.468065 3.424600 2.667044 2.623021 4.055215
> diag(M5)<-NA > M5
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] NA 3.017767 2.923270 2.532730 3.425423 [2,] 2.742611 NA 4.906797 4.273442 3.416288 [3,] 2.744358 4.227648 NA 3.508798 3.423980 [4,] 3.124375 2.363392 3.336010 NA 3.294046 [5,] 3.468065 3.424600 2.667044 2.623021 NA