[R] Reshape by multiple variables

Thomas Lumley tlumley at u.washington.edu
Tue Nov 26 20:38:23 CET 2002


On Tue, 26 Nov 2002, Laura Gross wrote:

> Dear list
>
> I'm using the reshape command and want to reshape a wide data set to a
> long one
>
> e.g. I have the variables y1,y2,y3,age1,age2,age3,sex,ethnic
>
> I want my new long data set to consist of the variables y (which has
> been created from y1,y2,y3), age (which has been created from
> age1,age2,age3), sex and ethnic
>
> I have tried to use the command:
>
> data1<-reshape(data,varying=list(c("y1","y2","y3"),c("age1","age2","age"
> )),v.names="y","age", times=1:3,direction="long")
>
> but it tells me I am trying to duplicate row names?
>
> How can I put multiple time-varying variables into the varying bit?

The command you gave has two clear errors: you forgot the 3 on age3 and
you didn't use c() around the v.names argument.  Even so, I don't get an
error message from it (just the wrong result).

With these corrected it works for me:

> data
  y1 y2  y3 age1 age2 age3    sex ethnic
1  1 11 101    5   25   35   male      1
2  2 12 102    6   26   36   male      2
3  3 13 103    7   27   37   male      3
4  4 14 104    8   28   38 female      4
5  5 15 105    9   29   39 female      5
> reshape(data,varying=list(c("y1","y2","y3"),c("age1","age2","age3")),v.names=c
("y","age"),times=1:3,direction="long")
       sex ethnic time   y age id
1.1   male      1    1   1   5  1
2.1   male      2    1   2   6  2
3.1   male      3    1   3   7  3
4.1 female      4    1   4   8  4
5.1 female      5    1   5   9  5
1.2   male      1    2  11  25  1
2.2   male      2    2  12  26  2
3.2   male      3    2  13  27  3
4.2 female      4    2  14  28  4
5.2 female      5    2  15  29  5
1.3   male      1    3 101  35  1
2.3   male      2    3 102  36  2
3.3   male      3    3 103  37  3
4.3 female      4    3 104  38  4
5.3 female      5    3 105  39  5


	-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