如何从R中的矩阵中查找列名和行名?
行名和列名函数用于定义矩阵的相应名称,如果我们要提取这些名称,则将使用相同的函数。例如,如果我们有一个名为M的矩阵,该矩阵具有行名和列名,则可以使用rownames(M) 和 colnames(M)。
示例
> M1<-matrix(1:100,ncol=10)输出结果> M1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10][1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
示例
> rownames(M1)<-LETTERS[1:10]输出结果> colnames(M1)<-LETTERS[1:10]
> M1
A B C D E F G H I JA 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
示例
> Row_Names_M1<-rownames(M1)输出结果> Row_Names_M1
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
示例
> Column_Names_M1<-colnames(M1)输出结果> Column_Names_M1
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
示例
> M2<-matrix(rpois(25,2),nrow=5)输出结果> M2
[,1] [,2] [,3] [,4] [,5][1,] 2 1 4 0 2
[2,] 3 3 0 3 3
[3,] 0 4 3 4 1
[4,] 4 1 0 1 0
[5,] 0 4 2 4 1
示例
> rownames(M2)<-c("India","Russia","China","Canada","USA")输出结果> colnames(M2)<-c("India","Russia","China","Canada","USA")
> M2
India Russia China Canada USAIndia 2 1 4 0 2
Russia 3 3 0 3 3
China 0 4 3 4 1
Canada 4 1 0 1 0
USA 0 4 2 4 1
示例
> Row_Names_M2<-rownames(M2)输出结果> Row_Names_M2
[1] "India" "Russia" "China" "Canada" "USA"
示例
Column_Names_M2<-colnames(M2)输出结果> Column_Names_M2
[1] "India" "Russia" "China" "Canada" "USA"
示例
> M3<-matrix(rnorm(36),nrow=6)输出结果> M3
[,1] [,2] [,3] [,4] [,5] [,6][1,] -0.81749436 -0.32603647 0.03249139 1.5090542 -0.9081710 1.2238853
[2,] -0.04507115 1.07842603 -1.11499780 0.4417905 -0.2758092 -0.9476823
[3,] -1.03613764 -2.65759584 -1.15795880 -1.9723598 -0.8386178 -0.2994112
[4,] 0.10289330 -0.06578772 -0.11692342 0.6313891 0.9125360 -0.2126542
[5,] 0.28185191 1.13375235 -0.47490971 0.2593980 -0.9350917 -0.4375274
[6,] 0.08914057 -0.32701974 1.25754633 -1.7432336 1.1584573 0.4017967
示例
> rownames(M3)<-c("C1","C2","C3","C4","C5","C6")输出结果> colnames(M3)<-c("S1","S2","S3","S4","S5","S6")
> M3
S1 S2 S3 S4 S5 S6C1 -0.81749436 -0.32603647 0.03249139 1.5090542 -0.9081710 1.2238853
C2 -0.04507115 1.07842603 -1.11499780 0.4417905 -0.2758092 -0.9476823
C3 -1.03613764 -2.65759584 -1.15795880 -1.9723598 -0.8386178 -0.2994112
C4 0.10289330 -0.06578772 -0.11692342 0.6313891 0.9125360 -0.2126542
C5 0.28185191 1.13375235 -0.47490971 0.2593980 -0.9350917 -0.4375274
C6 0.08914057 -0.32701974 1.25754633 -1.7432336 1.1584573 0.4017967
示例
> Row_Names_M3<-rownames(M3)输出结果> Row_Names_M3
[1] "C1" "C2" "C3" "C4" "C5" "C6"
示例
> Column_Names_M3<-colnames(M3)输出结果> Column_Names_M3
[1] "S1" "S2" "S3" "S4" "S5" "S6"
以上是 如何从R中的矩阵中查找列名和行名? 的全部内容, 来源链接: utcz.com/z/345232.html