[R] Struchture change of a data frame

Achim Zeileis zeileis at ci.tuwien.ac.at
Thu May 16 01:56:23 CEST 2002


Beat Huggler wrote:
> 
> Hi guys
> 
> I've got an easy question but couldn't find any quick solution. I woulk
> like to change the following matrix
> 
>                 good    bad worse
> Blue            1       2       2
> Yellow  2       1       3
> Black           3       4       4
> 
> Into the following structure
> 
> good    1       Blue
> Bad     2       Blue
> Worse   2       Blue
> Good    2       Yellow
> Bad     1       Yellow
> Worse   2       Yellow
> Good    2       Black
> Bad     4       Black
> Worse   4       Black

If your problem is that simple, you can do the following: starting from
a matrix
R> my.matrix
       good bad worse
Blue      1   2     2
Yellow    2   1     3
Black     3   4     4

You can simply say:
R> as.data.frame(as.table(my.matrix))
    Var1  Var2 Freq
1   Blue  good    1
2 Yellow  good    2
3  Black  good    3
4   Blue   bad    2
5 Yellow   bad    1
6  Black   bad    4
7   Blue worse    2
8 Yellow worse    3
9  Black worse    4

If your problem is more complex, then use reshape() as Thomas suggested.
Best,
Z

> Thanks a lot.
> 
> Regards
> 
> Beat Huggler
> 
> ---
> Beat Huggler
> Quantitative Analysis
> RMF Investment Products
> Huobstrasse 16
> 8808 Pfaeffikon SZ
> Switzerland
> www.rmf.ch
> Tel. +41 55 415 87 30
> Fax +41 55 415 87 07
> 
> This message and any attachment are confidential and may be privileged
> or otherwise protected from disclosure.  If you are not the intended
> recipient, please telephone or email the sender and delete this message
> and any attachment from your system.  If you are not the intended
> recipient you must not copy this message or attachment or disclose the
> contents to any other person.
> 
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list