[R] from matrix to data.frame
jim holtman
jholtman at gmail.com
Tue Jan 20 15:56:17 CET 2009
the reshape package might also help:
> require(reshape)
> x
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
> melt(t(x))
X1 X2 value
1 A 1 1
2 B 1 6
3 C 1 11
4 D 1 16
5 E 1 21
6 A 2 2
7 B 2 7
8 C 2 12
9 D 2 17
10 E 2 22
11 A 3 3
12 B 3 8
13 C 3 13
14 D 3 18
15 E 3 23
16 A 4 4
17 B 4 9
18 C 4 14
19 D 4 19
20 E 4 24
21 A 5 5
22 B 5 10
23 C 5 15
24 D 5 20
25 E 5 25
On Tue, Jan 20, 2009 at 9:10 AM, Antje <niederlein-rstat at yahoo.de> 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list