# [R] from matrix to data.frame

Marc Schwartz marc_schwartz at comcast.net
Tue Jan 20 15:38:32 CET 2009

```on 01/20/2009 08:10 AM Antje wrote:
> Hello,
>
> I have a question how to reshape a given matrix to a data frame.
>
> # ----------------------------------
>> a <- matrix(1:25, nrow=5)
>> a
>      [,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(a) <- LETTERS[1:5]
>> rownames(a) <- as.character(1:5)
>> a
>   A  B  C  D  E
> 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
>
> # -----------------------------------
>
> This is an example on how my matrix looks like.
> Now, I'd like to reshape the data that I get a data frame with three
> columns:
>
> - the row name of the enty (X1)
> - the column name of the entry (X2)
> - the entry itself (X3)
>
> like:
>
> X1    X2    X3
> 1    A    1
> 2    A    2
> 3    A    3
> ....
> 1    B    6
> 2    B    7
> ....
> 5    E    25
>
> How would you solve this problem in an elegant way?
>
> Antje

See ?as.data.frame.table

DF.a <- as.data.frame.table(a)

colnames(DF.a) <- paste("X", 1:ncol(DF.a), sep = "")

> DF.a
X1 X2 X3
1   1  A  1
2   2  A  2
3   3  A  3
4   4  A  4
5   5  A  5
6   1  B  6
7   2  B  7
8   3  B  8
9   4  B  9
10  5  B 10
11  1  C 11
12  2  C 12
13  3  C 13
14  4  C 14
15  5  C 15
16  1  D 16
17  2  D 17
18  3  D 18
19  4  D 19
20  5  D 20
21  1  E 21
22  2  E 22
23  3  E 23
24  4  E 24
25  5  E 25

HTH,

Marc Schwartz

```

More information about the R-help mailing list