使用矩阵函数作为收集器

时间:2014-05-02 13:09:48

标签: r matrix

我想使用矩阵作为CD的所有观察的容器,在我的模拟中为下面的数据框产生20乘3的矩阵;

Nsimdata=function(ns,tp,mu,sigma2){
   x1=rnorm(ns)
   x2=rnorm(ns)
   x3=rnorm(ns)
   U=c(x1,x2,x3)
   simdata=data.frame(CD=U,ID=1:ns,
                   Time=factor(rep(c(1,2,3),each=ns)),
                   treatment=sample(rep(c('Trt','placebo'),ns/2)))
   #ans[k,]=table(simdata$treatment)
   simdata
}

所以这就是我所做的

ns=20
nsim=2
tp=3
YK=matrix(0,nrow=ns,ncol=tp)
for(i in 1:nsim){
   DD=Nsimdata(ns,tp,mu,sigma2)
   for(j in 1:tp){
      Y=subset(DD,Time==j,select=c(CD))
      Y=Y$CD
      X=c(rep(0,ns/2),rep(1,ns/2))
   }
}

我希望将我的数据框中的CD下的所有观察结果都记录到YK中。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

为什么不按照您希望数据结束的方式编写模拟功能?

# function to simulate the data
fnSimData = function(iSampleSize, iT, dMu = NULL, dSigma2 = NULL) {
  mU = matrix(rnorm(iSampleSize*3), ncol = 3, nrow = iSampleSize)
  simdata = data.frame(outcome.time = mU, 
                       idx = seq.int(iSampleSize),
                       treatment = sample(rep(c('Treatment','Placebo'), iSampleSize/2)))
  return(simdata)
} 

# parameters
iSampleSize = 20  # sample size
iNumSim = 2  # number of simulations
iT = 3  # number of time periods

# simulate the data
fnSimData(iSampleSize, iT, dMu, dSigma2)