如何将重复的行名和列名更改为R中矩阵的序列?

要将重复的行名和列名更改为序列,我们首先需要在向量中读取这些名称,然后使用make.unique功能将它们设置为行名和列名。例如,如果矩阵的行名定义为A,B,A,B,A,则可以将其转换为A,B,A.1,B.1,A.2。

例1

M1<−matrix(1:25,ncol=5)

M1

输出结果
   [,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

示例

colnames(M1)<−c("A","B","A","A","B")

rownames(M1)<−c("C","D","D","C","C")

M1

输出结果
  A B A  A  B

C 1 6 11 16 21

D 2 7 12 17 22

D 3 8 13 18 23

C 4 9 14 19 24

C 5 10 15 20 25

示例

C1<−c("A","B","A","A","B")

colnames(M1)<−make.unique(C1)

R1<−c("C","D","D","C","C")

rownames(M1)<−make.unique(R1)

M1

输出结果
  A B A.1 A.2 B.1

C 1 6 11 16   21

D 2 7 12 17   22

D.1 3  8 13   18 23

C.1 4  9 14   19 24

C.2 5 10 15   20 25

例2

M2<−matrix(rnorm(25),nrow=5)

M2

输出结果
      [,1]          [,2]       [,3]       [,4]       [,5]

[1,] −0.9603079 2.7738930 −1.68887845 −0.3516074 2.237315508

[2,] −0.3346606 −1.2140159 −0.08791009 −0.3596462 −0.009851671

[3,] 0.7399818 −2.1791770 −1.70416955 0.2715390 −0.766143519

[4,] 1.1195890 −1.7790965 0.09878024 −0.4761445 1.859189587

[5,] −1.3238430 0.2936939 −2.15993049 −0.9182923 −0.647121554

示例

colnames(M2)<−c("Hot","Cold","Cold","Hot","Hot")

rownames(M2)<−c("Asian","Americas","Americas","Asian","Americas")

M2

输出结果
Hot Cold Cold Hot Hot

Asian −0.9603079 2.7738930 −1.68887845 −0.3516074 2.237315508

Americas −0.3346606 −1.2140159 −0.08791009 −0.3596462 −0.009851671

Americas 0.7399818 −2.1791770 −1.70416955 0.2715390 −0.766143519

Asian 1.1195890 −1.7790965 0.09878024 −0.4761445 1.859189587

Americas −1.3238430 0.2936939 −2.15993049 −0.9182923 −0.647121554

示例

C2<−c("Hot","Cold","Cold","Hot","Hot")

colnames(M2)<−make.unique(C2)

R2<−c("Asian","Americas","Americas","Asian","Americas")

rownames(M2)<−make.unique(R2)

M2

输出结果
Hot Cold Cold.1 Hot.1 Hot.2

Asian −0.9603079 2.7738930 −1.68887845 −0.3516074 2.237315508

Americas −0.3346606 −1.2140159 −0.08791009 −0.3596462 −0.009851671

Americas.1 0.7399818 −2.1791770 −1.70416955 0.2715390 −0.766143519

Asian.1 1.1195890 −1.7790965 0.09878024 −0.4761445 1.859189587

Americas.2 −1.3238430 0.2936939 −2.15993049 −0.9182923 −0.647121554

范例3

M3<−matrix(sample(c(21:50),16),nrow=4)

M3

输出结果
   [,1] [,2] [,3] [,4]

[1,] 36  46   26   21

[2,] 42  24   34   50

[3,] 37  33   43   27

[4,] 45  30   49   39

示例

colnames(M3)<−c("V1","V1","V2","V2")

rownames(M3)<−c("case1","case2","case2","case1")

M3

输出结果
      V1 V1 V2 V2

case1 36 46 26 21

case2 42 24 34 50

case2 37 33 43 27

case1 45 30 49 39

示例

C3<−c("V1","V1","V2","V2")

colnames(M3)<−make.unique(C3)

R3<−c("case1","case2","case2","case1")

rownames(M3)<−make.unique(R3)

M3

输出结果
     V1 V1.1 V2 V2.1

case1 36 46 26 21

case2 42 24 34 50

case2.1 37 33 43 27

case1.1 45 30 49 39

以上是 如何将重复的行名和列名更改为R中矩阵的序列? 的全部内容, 来源链接: utcz.com/z/314260.html

回到顶部