[R] from matrix to data.frame

Antje niederlein-rstat at yahoo.de
Tue Jan 20 15:10:41 CET 2009


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




More information about the R-help mailing list