如何使用R模拟纵向数据

时间:2014-06-30 20:22:02

标签: r simulation

我想模拟模型中的纵向数据

Y_ij = beta_1 * X_1i + beta_2 * X_2i + beta_3 * t_ij + beta_4 * X_1i * t_ij + beta_5 * X_2i t_ij + b_1i + b_2i t_ij + e_ij

我尝试使用以下代码

library(MASS)
library(nlme)

#True values of the parameter
beta0 <- 0
beta1 <- 2
beta2 <- -1
beta3 <- 2
beta4 <- -2
beta5 <- 1.5
sigmab <- matrix(c(.5,-.1,-.1,.25),byrow=T,nrow=2)


#Covariates
X1i <- rbinom(n=200,size=1,prob=.5)
X2i <- rnorm(n=200,mean=2,sd=.4)

#
bi <- mvrnorm(200,mu=c(0,0),Sigma=sigmab)

j <- round(runif(200,2,4))
tij <- unlist(sapply(j, function(x) (.2*(1:x-1))))
dat <- data.frame(id=rep(1:200,times=j),obstime=tij)
dat$X1i <- rep(X1i,times=j)
dat$X2i <- rep(X2i,times=j)
dat$eij <- unlist(sapply(j, function(x) rnorm(x,mean=0,sd=sqrt(.1))))
dat$b1i <- rep(bi[,1],times=j)
dat$b2i <- rep(bi[,2],times=j)
dat$yij <- with(dat, beta0 + beta1*X1i + beta2*X2i + beta3*obstime
    + beta4*X1i*obstime + beta5*X2i*obstime + b1i + b2i*obstime
        + eij)

dat <- groupedData(yij~(X1i+ X2i)*obstime | id ,data=dat)

lme.fit <- lme(yij~(X1i*obstime)+(X2i*obstime),random=~obstime|id,data=dat)

但是lme.fit会给出错误消息

Error in lme.formula(yij ~ (X1i * obstime) + (X2i * obstime), random = ~obstime |  : 
  nlminb problem, convergence error code = 1
  message = iteration limit reached without convergence (10)

请有人帮我解决问题。

0 个答案:

没有答案