I am trying to use lme inside a function I am writing to fit a longitudinal mixed effect model to three level data (e.g. centre at level 3, with individuals nested inside at level 2, with longitudinal measurements at level 1). I want to specify some random effects that act only at level 3 (example using treatment) and some that act only at level 2 (example using time). After a bit of research, I found I can do this by specifying the random effects using:
random=list(centre=~treat,id=~time)
modelfit<-lme(...,random=list(centre=~treat,id=~time))
This should give me a random intercept and random treatment term at level 3, and a random intercept and random time term at level 2. This works if I type the model out in full each time. However I want to use paste() to create the necessary formula from the variable names from the dataset supplied to the function. I had successfully used paste to specify random effects previously when they were specified using the following structure:
random=~time|id
However when I now wrap the centre=~treat in as.formula, it removes the centre= , just leaving ~1+treat, and then the model gives an error. Below I've typed out an example of the kind of thing I'm trying to do. I'm sorry I haven't included any data.
test1<-c("time")
test2<-c("treat")
id.name<-"id"
centre.name<-"centre
rf.ind<-as.formula(paste(id.name,paste("~1",paste(test1,collapse="+"),sep="+"),sep="=")
rf.centre<-as.formula(paste(centre.name,paste("~1",paste(test2,collapse="+"),sep="+"),sep="=")
modelfit<-lme(...random=list(rf.centre,rf.ind))
Please could someone tell me if there is a method to specify random effects using a list in this way, but pasting variable names from a dataset, avoiding the problems I am facing with as.formula? Or is there a different way to specify a longitudinal model with different random effects at different levels? I'm sorry that there is not a fully reproducible example here. Thanks!
Aucun commentaire:
Enregistrer un commentaire