矩阵转为ggplot2画图的数据格式

作者:ahworld
链接:转换矩阵为ggplot2的输入格式
来源:微信公众号-seqyuan
著作权归作者所有,任何形式的转载都请联系作者。

在使用ggplot2画图时,如果拿到的数据是N x N的,那么画图很不方便,需要转换成行列名称为新的列的标识

下面的代码提供了转换的方法

M1 <- data.frame(matrix(1:25,nrow=5,dimnames=list(c("R1","R2","R3","R4","R5"),c("S1","S2","S3","S4","S5"))))
M1$S1 <- c("A1","A1","A2","A2","A2")
M1$S2 <- c("B1","B1","B1","B2","B2")
M1
S1 S2 S3 S4 S5
R1 A1 B1 11 16 21
R2 A1 B1 12 17 22
R3 A2 B1 13 18 23
R4 A2 B2 14 19 24
R5 A2 B2 15 20 25
rownames(M1) <- paste(rownames(M1), M1$S1, M1$S2, sep="-")
M2 <- subset(M1, select=c("S3","S4","S5"))
M2 <- as.data.frame(as.table(as.matrix(M2)))
M2
Var1 Var2 Freq
1 R1-A1-B1 S3 11
2 R2-A1-B1 S3 12
3 R3-A2-B1 S3 13
4 R4-A2-B2 S3 14
5 R5-A2-B2 S3 15
6 R1-A1-B1 S4 16
7 R2-A1-B1 S4 17
8 R3-A2-B1 S4 18
9 R4-A2-B2 S4 19
10 R5-A2-B2 S4 20
11 R1-A1-B1 S5 21
12 R2-A1-B1 S5 22
13 R3-A2-B1 S5 23
14 R4-A2-B2 S5 24
15 R5-A2-B2 S5 25
library(stringr)
Var1 <- data.frame(str_split_fixed(M2$Var1, "-", 3))
M2 <- cbind(Var1, M2)
M2 <- M2[,-4]
M2
X1 X2 X3 Var2 Freq
1 R1 A1 B1 S3 11
2 R2 A1 B1 S3 12
3 R3 A2 B1 S3 13
4 R4 A2 B2 S3 14
5 R5 A2 B2 S3 15
6 R1 A1 B1 S4 16
7 R2 A1 B1 S4 17
8 R3 A2 B1 S4 18
9 R4 A2 B2 S4 19
10 R5 A2 B2 S4 20
11 R1 A1 B1 S5 21
12 R2 A1 B1 S5 22
13 R3 A2 B1 S5 23
14 R4 A2 B2 S5 24
15 R5 A2 B2 S5 25

参考:

https://www.tutorialspoint.com/how-to-convert-a-matrix-to-a-data-frame-with-column-names-and-row-names-as-new-columns-in-r

你可能感兴趣的:(矩阵转为ggplot2画图的数据格式)