[R] Can't get the correct order from melt.data.frame of reshape library.

jim holtman jholtman at gmail.com
Sat Jul 26 20:59:41 CEST 2008


Is this what you want:

> df3 <- data.frame(id=c(3,2,1,4), age=c(40,50,60,50), dose1=c(1,2,1,2), dose2=c(2,1,2,1), dose4=c(3,3,3,3))
> df3
  id age dose1 dose2 dose4
1  3  40     1     2     3
2  2  50     2     1     3
3  1  60     1     2     3
4  4  50     2     1     3
> new.df <- melt.data.frame(df3, id.var=1:2, na.rm=T)
> # use the order in df3 to create factors in new.df
> new.df$id <- factor(new.df$id, levels=df3$id)
> new.df[order(new.df$id),]
   id age variable value
1   3  40    dose1     1
5   3  40    dose2     2
9   3  40    dose4     3
2   2  50    dose1     2
6   2  50    dose2     1
10  2  50    dose4     3
3   1  60    dose1     1
7   1  60    dose2     2
11  1  60    dose4     3
4   4  50    dose1     2
8   4  50    dose2     1
12  4  50    dose4     3
>


On Sat, Jul 26, 2008 at 12:00 PM, Daren Tan <daren76 at hotmail.com> wrote:
>
> Simple illustration,
>
>> df3 <- data.frame(id=c(3,2,1,4), age=c(40,50,60,50), dose1=c(1,2,1,2), dose2=c(2,1,2,1), dose4=c(3,3,3,3))> df3  id age dose1 dose2 dose41  3  40     1     2     32  2  50     2     1     33  1  60     1     2     34  4  50     2     1     3> melt.data.frame(df3, id.var=1:2, na.rm=T)   id age variable value1   3  40    dose1     12   2  50    dose1     23   1  60    dose1     14   4  50    dose1     25   3  40    dose2     26   2  50    dose2     17   1  60    dose2     28   4  50    dose2     19   3  40    dose4     310  2  50    dose4     311  1  60    dose4     312  4  50    dose4     3
>
> My objective is to get the below such that the "long" form is in the same order as the "id" column of df3.
>   id age variable value1   3  40    dose1     12   3  40    dose2     2
> 3   3  40    dose4     3
> 4   2  50    dose1     25   2  50    dose2     1
> 6   2  50    dose4     3
> 7   1  60    dose1     18   1  60    dose2     2
> 9   1  60    dose4     3
> 10   4  50    dose1     211   4  50    dose2     112  4  50    dose4     3
> _________________________________________________________________
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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 you are trying to solve?



More information about the R-help mailing list