[R] from matrix to data.frame

jim holtman jholtman at gmail.com
Tue Jan 20 15:51:31 CET 2009


?stack

> x <- read.table(textConnection(" 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"), header=TRUE)
>
> 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
> stack(x)
   values ind
1       1   A
2       2   A
3       3   A
4       4   A
5       5   A
6       6   B
7       7   B
8       8   B
9       9   B
10     10   B
11     11   C
12     12   C
13     13   C
14     14   C
15     15   C
16     16   D
17     17   D
18     18   D
19     19   D
20     20   D
21     21   E
22     22   E
23     23   E
24     24   E
25     25   E
>


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