如何使用行名在R中创建矩阵的子集?
当我们在R中创建矩阵时,未定义行名和列名,但可以分别定义它们。如果要获取矩阵行的子集,则可以在单个方括号内使用行号,但是如果要使用名称来做,则需要指定这些名称。
示例
M1<-matrix(1:25,ncol=5) rownames(M1)<-letters[1:5] M1
输出结果
[,1] [,2] [,3] [,4] [,5] a 1 6 11 16 21 b 2 7 12 17 22 c 3 8 13 18 23 d 4 9 14 19 25
示例
M1[c("a","b"),]
输出结果
[,1] [,2] [,3] [,4] [,5] a 1 6 11 16 21 b 2 7 12 17 22
示例
M1[c("a","d"),]
输出结果
[,1] [,2] [,3] [,4] [,5] a 1 6 11 16 21 d 4 9 14 19 24
示例
M1[c("a","e"),]
输出结果
[,1] [,2] [,3] [,4] [,5] a 1 6 11 16 21 e 5 10 15 20 25
示例
M1[c("a","b","e"),]
输出结果
[,1] [,2] [,3] [,4] [,5] a 1 6 11 16 21 b 2 7 12 17 22 e 5 10 15 20 25
示例
M1[c("a","b","d","e"),]
输出结果
[,1] [,2] [,3] [,4] [,5] a 1 6 11 16 21 b 2 7 12 17 22 d 4 9 14 19 24 e 5 10 15 20 25
示例
M2<-matrix(1:100,nrow=10) rownames(M2)<-LETTERS[1:10] M2
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] A 1 11 21 31 41 51 61 71 81 91 B 2 12 22 32 42 52 62 72 82 92 C 3 13 23 33 43 53 63 73 83 93 D 4 14 24 34 44 54 64 74 84 94 E 5 15 25 35 45 55 65 75 85 95 F 6 16 26 36 46 56 66 76 86 96 G 7 17 27 37 47 57 67 77 87 97 H 8 18 28 38 48 58 68 78 88 98 I 9 19 29 39 49 59 69 79 89 99 J 10 20 30 40 50 60 70 80 90 100
示例
M2[c("A","J"),]
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] A 1 11 21 31 41 51 61 71 81 91 J 10 20 30 40 50 60 70 80 90 100
示例
M2[c("A","D","F","I"),]
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] A 1 11 21 31 41 51 61 71 81 91 D 4 14 24 34 44 54 64 74 84 94 F 6 16 26 36 46 56 66 76 86 96 I 9 19 29 39 49 59 69 79 89 99
示例
M2[c("A","C","E","G","J"),]
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] A 1 11 21 31 41 51 61 71 81 91 C 3 13 23 33 43 53 63 73 83 93 E 5 15 25 35 45 55 65 75 85 95 G 7 17 27 37 47 57 67 77 87 97 J 10 20 30 40 50 60 70 80 90 100
示例
M3<-matrix(rnorm(25,1,0.04),nrow=5) rownames(M3)<-c("Rate1","Rate2","Rate3","Rate4","Rate5") M3
输出结果
[,1] [,2] [,3] [,4] [,5] Rate1 1.0095550 0.9804156 0.9655588 1.025432 0.9420430 Rate2 0.9926681 0.9830571 0.9428085 1.000219 0.9980977 Rate3 1.0039020 1.0121637 1.0291146 1.062020 1.0822971 Rate4 1.0720653 1.0469583 0.9947673 1.065848 1.0165283 Rate5 0.9752784 1.0382877 0.9933063 1.011313 0.9942537
示例
M3["Rate3",]
输出结果
[1] 1.003902 1.012164 1.029115 1.062020 1.082297
示例
M3[c("Rate1","Rate5"),]
输出结果
[,1] [,2] [,3] [,4] [,5] Rate1 1.0095550 0.9804156 0.9655588 1.025432 0.9420430 Rate5 0.9752784 1.0382877 0.9933063 1.011313 0.9942537
示例
M3[c("Rate1","Rate3","Rate5"),]
输出结果
[,1] [,2] [,3] [,4] [,5] Rate1 1.0095550 0.9804156 0.9655588 1.025432 0.9420430 Rate3 1.0039020 1.0121637 1.0291146 1.062020 1.0822971 Rate5 0.9752784 1.0382877 0.9933063 1.011313 0.9942537