如何创建 R 中矩阵的行列子集?
矩阵可以像数据帧一样具有多行多列。与数据帧一样,有时候我们需要获取子集,对于矩阵来说也是如此。但是,与子集数据帧相比,子集矩阵数据非常简单。
示例
考虑以下矩阵 −
> 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
广告