[R] Randomly interleaving data frames while preserving order

Tom Wright tom at maladmin.com
Tue Mar 31 19:59:56 CEST 2015


samples<-sample(c(rep(1,10),rep(2,10),rep(3,10)),30)
samples[samples==1]<-1001:1010
samples[samples==2]<-2001:2010
samples[samples==3]<-3001:3010

fullDf<-rbind(df1,df2,df3)

fullDf[sort(order(samples),index.return=TRUE)$ix,]

On Tue, 2015-03-31 at 13:05 -0400, Kevin E. Thorpe wrote:
> Hello.
> 
> I am trying to simulate recruitment in a randomized trial. Suppose I 
> have three streams (strata) of patients represented by these data frames.
> 

> 
> What I need to do is construct a data frame with all of these combined 
> where the order of selection from one of the three data frames is 
> randomized but once a stratum is selected patients are selected 
> sequentially from that data frame.
> 
> To see what I'm looking to achieve, suppose the first five subjects were 
> to come, in order, from strata (data frames) 1, 2, 1, 3 and 2. The 
> expected result should look like this:
> 
> rbind(df1[1,],df2[1,],df1[2,],df3[1,],df2[2,])
>     strat id  pid
> 1      1  1 1001
> 2      2  1 2001
> 21     1  2 1002
> 4      3  1 3001
> 22     2  2 2002
> 
> I hope what I'm trying to accomplish makes sense. Maybe I'm missing 
> something obvious, but I really have no idea at the moment how to 
> achieve this elegantly. Since I need to simulate many trial recruitments 
> it needs to be general and compact.
> 
> I appreciate any advice.
> 
> Kevin
>



More information about the R-help mailing list