[R] from matrix to data.frame

Carlos J. Gil Bellosta cgb at datanalytics.com
Tue Jan 20 15:33:13 CET 2009


Hello, 

The columns in your output dataframe are the following vectors:

X1:	as.vector( row(a) )
X2:	colnames(a)[as.vector( col(a) )]
X3:	as.vector( a )

Best regards,

Carlos J. Gil Bellosta
http://www.datanalytics.com

On Tue, 2009-01-20 at 15:10 +0100, 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
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list