如何在R中将矩阵转换为数据框,并将列名和行名作为新列?
有时我们希望创建矩阵的列名和行名的因子列,以便在分析中使用它们。当我们想要了解因子变量对响应的影响,并且因子变量在矩阵中以列名和行名的形式记录时,这种情况是需要的。为此,我们可以将矩阵转换为表格,然后将得到的表格转换为数据框。
示例
考虑以下矩阵:
M1<-matrix(1:25,nrow=5,dimnames=list(c("R1","R2","R3","R4","R5"),c("S1","S2","S3","S4","S5"))) M1
输出
S1 S2 S3 S4 S5 R1 1 6 11 16 21 R2 2 7 12 17 22 R3 3 8 13 18 23 R4 4 9 14 19 24 R5 5 10 15 20 25
示例
as.data.frame(as.table(M1))
输出
Var1 Var2 Freq 1 R1 S1 1 2 R2 S1 2 3 R3 S1 3 4 R4 S1 4 5 R5 S1 5 6 R1 S2 6 7 R2 S2 7 8 R3 S2 8 9 R4 S2 9 10 R5 S2 10 11 R1 S3 11 12 R2 S3 12 13 R3 S3 13 14 R4 S3 14 15 R5 S3 15 16 R1 S4 16 17 R2 S4 17 18 R3 S4 18 19 R4 S4 19 20 R5 S4 20 21 R1 S5 21 22 R2 S5 22 23 R3 S5 23 24 R4 S5 24 25 R5 S5 25
让我们再看两个例子:
M2<-matrix(sample(1:50,16),nrow=4,dimnames=list(c("R1","R2","R3","R4"),c("C1","C2","C3","C4"))) M2
输出
C1 C2 C3 C4 R1 38 23 30 34 R2 17 19 32 10 R3 9 26 47 1 R4 39 43 29 44
示例
as.data.frame(as.table(M2))
输出
Var1 Var2 Freq 1 R1 C1 38 2 R2 C1 17 3 R3 C1 9 4 R4 C1 39 5 R1 C2 23 6 R2 C2 19 7 R3 C2 26 8 R4 C2 43 9 R1 C3 30 10 R2 C3 32 11 R3 C3 47 12 R4 C3 29 13 R1 C4 34 14 R2 C4 10 15 R3 C4 1 16 R4 C4 44
示例
M3 <-matrix(sample(1:100,16),ncol=4,dimnames=list(c("Cold","Hot","Sweet","Bitter"),c("Winter","Autumn","Rainy","Summer"))) > M3
输出
Winter Autumn Rainy Summer Cold 15 42 97 83 Hot 58 48 53 35 Sweet 29 76 86 43 Bitter 24 39 40 1
示例
as.data.frame(as.table(M3))
输出
Var1 Var2 Freq 1 Cold Winter 15 2 Hot Winter 58 3 Sweet Winter 29 4 Bitter Winter 24 5 Cold Autumn 42 6 Hot Autumn 48 7 Sweet Autumn 76 8 Bitter Autumn 39 9 Cold Rainy 97 10 Hot Rainy 53 11 Sweet Rainy 86 12 Bitter Rainy 40 13 Cold Summer 83 14 Hot Summer 35 15 Sweet Summer 43 16 Bitter Summer 1
广告