How to convert a matrix into a data frame with column names and row names as variables in R?

R ProgrammingServer Side ProgrammingProgramming

To convert a matrix into a data frame with column names and row names as variables, we first need to convert the matrix into a table and then read it as data frame using as.data.frame. For example, if we have a matrix M then it can be done by using the below command −

as.data.frame(as.table(M))

Example1

Live Demo

> M1<-matrix(1:36,nrow=6)
> M1

Output

[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 7 13 19 25 31
[2,] 2 8 14 20 26 32
[3,] 3 9 15 21 27 33
[4,] 4 10 16 22 28 34
[5,] 5 11 17 23 29 35
[6,] 6 12 18 24 30 36

Example

> rownames(M1)<-1:6
> colnames(M1)<-LETTERS[1:6]
> M1

Output

A B C D E F
1 1 7 13 19 25 31
2 2 8 14 20 26 32
3 3 9 15 21 27 33
4 4 10 16 22 28 34
5 5 11 17 23 29 35
6 6 12 18 24 30 36

Example

> as.data.frame(as.table(M1))

Output

Var1 Var2 Freq
1 1 A 1
2 2 A 2
3 3 A 3
4 4 A 4
5 5 A 5
6 6 A 6
7 1 B 7
8 2 B 8
9 3 B 9
10 4 B 10
11 5 B 11
12 6 B 12
13 1 C 13
14 2 C 14
15 3 C 15
16 4 C 16
17 5 C 17
18 6 C 18
19 1 D 19
20 2 D 20
21 3 D 21
22 4 D 22
23 5 D 23
24 6 D 24
25 1 E 25
26 2 E 26
27 3 E 27
28 4 E 28
29 5 E 29
30 6 E 30
31 1 F 31
32 2 F 32
33 3 F 33
34 4 F 34
35 5 F 35
36 6 F 36

Example2

Live Demo

> M2<-matrix(rnorm(25),nrow=5)
> M2

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455
[2,] 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560
[3,] 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002
[4,] 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883
[5,] -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645

Example

> rownames(M2)<-c("R1","R2","R3","R4","R5")
> colnames(M2)<-c("C1","C2","C3","C4","C5")
> M2

Output

C1 C2 C3 C4 C5
R1 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455
R2 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560
R3 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002
R4 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883
R5 -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645

Example

> as.data.frame(as.table(M2))

Output

Var1 Var2 Freq
1 R1 C1 0.18116436
2 R2 C1 0.32326518
3 R3 C1 0.44080495
4 R4 C1 2.99376289
5 R5 C1 -0.94482784
6 R1 C2 0.11869776
7 R2 C2 1.45457299
8 R3 C2 -0.14029090
9 R4 C2 -0.18043699
10 R5 C2 -0.26155322
11 R1 C3 -0.48697926
12 R2 C3 -1.81291997
13 R3 C3 -0.08482793
14 R4 C3 -0.05752013
15 R5 C3 -0.05046240
16 R1 C4 -1.12666228
17 R2 C4 1.88503065
18 R3 C4 0.50073769
19 R4 C4 -2.70116904
20 R5 C4 -0.99943242
21 R1 C5 0.34164554
22 R2 C5 -1.76415604
23 R3 C5 0.27540019
24 R4 C5 -0.16288833
25 R5 C5 1.45886447
raja
Published on 05-Jan-2021 06:01:36
Advertisements