矩阵可以像数据框一样具有多个行和列。就像在数据框中一样,有时我们需要获取子集,而矩阵也可能需要同样的子集。但是子集矩阵数据与子集数据帧相比非常简单。
考虑下面的矩阵-
> M<-matrix(1:25,5) > M [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
矩阵M的子集列-
> M[,1,drop=FALSE] [,1] [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5 > M[,3,drop=FALSE] [,1] [1,] 11 [2,] 12 [3,] 13 [4,] 14 [5,] 15 > M[,5,drop=FALSE] [,1] [1,] 21 [2,] 22 [3,] 23 [4,] 24 [5,] 25
子集矩阵M-
> M[1,,drop=FALSE] [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 > M[3,,drop=FALSE] [,1] [,2] [,3] [,4] [,5] [1,] 3 8 13 18 23 > M[5,,drop=FALSE] [,1] [,2] [,3] [,4] [,5] [1,] 5 10 15 20 25
创建一个具有列名和行名的新矩阵,如下所示:
> M_new<-matrix(c(25,23,25,20,15,17,13,19,25,24,21,19,20,12,30,17),ncol=4) > M_new [,1] [,2] [,3] [,4] [1,] 25 15 25 20 [2,] 23 17 24 12 [3,] 25 13 21 30 [4,] 20 19 19 17 > colnames(M_new)<-c("C1","C2","C3","C4") > rownames(M_new)<-c("R1","R2","R3","R4") > M_new C1 C2 C3 C4 R1 25 15 25 20 R2 23 17 24 12 R3 25 13 21 30 R4 20 19 19 17
子集M_new的列和行-
> M_new[,1,drop=FALSE] C1 R1 25 R2 23 R3 25 R4 20 > M_new[,3,drop=FALSE] C3 R1 25 R2 24 R3 21 R4 19 > M_new[1,,drop=FALSE] C1 C2 C3 C4 R1 25 15 25 20 > M_new[4,,drop=FALSE] C1 C2 C3 C4 R4 20 19 19 17