[R] Struchture change of a data frame
Thomas Lumley
tlumley at u.washington.edu
Wed May 15 17:49:34 CEST 2002
On Wed, 15 May 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
>
reshape() will do this, but you need a dataframe and need the `colors' to
be a column of the data frame, so if it is really a matrix
df<-as.data.frame(X)
df$colors<-colnames(X)
A simple version is
reshape(df,direction=long, varying=list(c("good","bad","worse")))
color time good id
1.1 Blue 1 1 1
2.1 Yellow 1 2 2
3.1 Black 1 2 3
1.2 Blue 2 2 1
2.2 Yellow 2 1 2
3.2 Black 2 4 3
1.3 Blue 3 2 1
2.3 Yellow 3 3 2
3.3 Black 3 4 3
and more precisely what you want is
reshape(df,direction="long",varying=list(c("good","bad","worse")),times=c("good","bad","worse"),idvar="color")
color time good
Blue.good Blue good 1
Yellow.good Yellow good 2
Black.good Black good 2
Blue.bad Blue bad 2
Yellow.bad Yellow bad 1
Black.bad Black bad 4
Blue.worse Blue worse 2
Yellow.worse Yellow worse 3
Black.worse Black worse 4
As you can see, reshape() is overdesigned for a problem like
this, but I assume your problem is in fact more complicated.
-thomas
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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