# How to convert a matrix to a data frame with column names and row names as new columns in R?

Sometimes we want to create a factor column of the column names and row names of a matrix so that we can use them in the analysis. It is required in situations where we want to know the effect of factor variables on the response and the factor variables were recorded as column names and row names in a matrix. To do this, we can convert the matrix into table and the table obtained is converted to data frame.

## Example

Consider the below matrix −

M1<-matrix(1:25,nrow=5,dimnames=list(c("R1","R2","R3","R4","R5"),c("S1","S2","S3","S4","S5")))
M1

## Output

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

## Example

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

## Output

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

Let’s have a look at two more examples −

M2<-matrix(sample(1:50,16),nrow=4,dimnames=list(c("R1","R2","R3","R4"),c("C1","C2","C3","C4")))
M2

## Output

C1 C2 C3 C4
R1 38 23 30 34
R2 17 19 32 10
R3 9 26 47 1
R4 39 43 29 44

## Example

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

## Output

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

## Example

M3 <-matrix(sample(1:100,16),ncol=4,dimnames=list(c("Cold","Hot","Sweet","Bitter"),c("Winter","Autumn","Rainy","Summer")))
> M3

## Output

Winter Autumn Rainy Summer
Cold 15 42 97 83
Hot 58 48 53 35
Sweet 29 76 86 43
Bitter 24 39 40 1

## Example

as.data.frame(as.table(M3))

## Output

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