Hi,

You could also do this by:
set.seed(15)
tr.df<-data.frame(ID=rep(1:29,each=3),prep=runif(87,1,3),postp=runif(87,0.5,1.5))
tr.df$time<-1:87
res<- reshape(tr.df, varying=2:3, v.name="value", 
times=c("prep","postp"),idvar="time",timevar="prepost",direction="long")
res<-res[order(res$ID,res$time),]
 row.names(res)<-1:nrow(res)
 head(res,4)
#  ID time prepost     value
#1  1    1    prep 2.2042281
#2  1    1   postp 1.3553657
#3  1    2    prep 1.3900879
#4  1    2   postp 0.8674933
A.K.



----- Original Message -----
From: Jim Lemon <j...@bitwrit.com.au>
To: Troels Ring <tr...@gvdnet.dk>
Cc: r-help@r-project.org
Sent: Tuesday, January 22, 2013 4:46 AM
Subject: Re: [R] simple reshape

On 01/22/2013 07:19 PM, Troels Ring wrote:
> Dear friends - this is a very simple question - I have a data frame
> 'data.frame': 87 obs. of 3 variables:
> $ ID : int 1 1 1 2 2 2 3 3 3 4 ...
> $ prep : num 1.18 1.38 1.34 1.93 2.38 2.24 1.17 1.13 1.21 1.89 ...
> $ postp: num 0.63 0.71 0.75 1.01 1.12 1.07 0.87 0.64 0.7 0.8 ...
>
> - 29 persons (ID) each measured three times before and after an
> intervention: prep and postp -
> I need data rearranged like
>
> ID time val
> 1 1 prep
> 1 2 postp
> 1 1
> 1 2
> 1 1
> 1 2
> I cannot make reshape or stack do the trick.
>
Hi Troels,
With a bit of extra processing I think rep_n_stack (prettyR) will do 
what you want:

# fake some data
tr.df<-data.frame(ID=rep(1:29,each=3),prep=runif(87,1,3),postp=runif(87,0.5,1.5))
# add a repeat number
tr.df$repno<-rep(1:3,29)
# get the reshaped data frame
trlong.df<-rep_n_stack(tr.df,to.stack=2:3,
  stack.names=c("prepost","value"))
# reorder it
trlong.df[order(trlong.df$ID,trlong.df$repno),]

     ID repno prepost     value
1    1     1    prep 2.9158693
88   1     1   postp 0.9932342
2    1     2    prep 1.2852817
89   1     2   postp 0.8187234
3    1     3    prep 2.5771902
90   1     3   postp 1.0033936
4    2     1    prep 2.2969320
91   2     1   postp 0.6837140
5    2     2    prep 1.3083553
92   2     2   postp 1.4537096
6    2     3    prep 2.8654184
93   2     3   postp 1.0880881
...

Jim

______________________________________________
R-help@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.


______________________________________________
R-help@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.

Reply via email to