r - Scoping-related (?): anova() on list of created mixed-effects models -
in project i'm performing mixed-effects modelling using lme
, i'm trying compare models different correlation structures , equal fixed parts. i'll building lot of these models (for different dependent variables), tried write function generate list of models different correlation structures, in example below (i tried keep minimum working example).
if run anova() on elements of list, works, only if fixedpart
in global environment. why case? there way circumvent problem, can keep m
, re-use/delete fixedpart
?
i presume problem related (lexical) scoping in r, cannot find way fix it.
thanks in advance!
#dependencies library(multilevel) library(multcomp) #generate sample data nvals = 100 sdata = rnorm(nvals, mean = 1, sd = 1) df <- data.frame(nsubject = 1:nvals, v1data = sdata + rnorm(nvals, mean = 0, sd = 0.1), v2data = sdata + rnorm(nvals, mean = 0, sd = 0.1), v3data = sdata + rnorm(nvals, mean = 0, sd = 0.4)) dlongf = reshape(data=df, varying=c("v1data","v2data","v3data"), v.names='data', direction="long", idvar="nsubject", times=1:3) #define function assess different covariance structures doallcorrmodels <- function(dataf, subjvarname, visitvarname, fixedpart){ mlist <- vector("list",2) mlist[[1]] <- lme(fixedpart, #random intercept, homogeneous variance random=as.formula(paste("~1|", subjvarname)), data=dataf, weights=null) mlist[[2]] <- lme(fixedpart, #random intercept, heterogeneous variance random=as.formula(paste("~1|", subjvarname)), data=dataf, weights=varident(form = as.formula(paste("~1|", visitvarname))) ) mlist } #get different covariance structures dataf <- dlongf subjvarname <- "nsubject" visitvarname <- "time" fixedpart <- data ~ time m <- doallcorrmodels(dataf, subjvarname, visitvarname, fixedpart) #this works: a1 <- anova(m[[1]], m[[2]]) #but not: rm(fixedpart) a2 <- anova(m[[1]], m[[2]])
you can avoid using do.call
:
doallcorrmodels <- function(dataf, subjvarname, visitvarname, fixedpart){ mlist <- vector("list",2) mlist[[1]] <- do.call(lme, list(fixed = fixedpart, random=as.formula(paste("~1|", subjvarname)), data=dataf, weights=null)) mlist[[2]] <- do.call(lme, list(fixed = fixedpart, random=as.formula(paste("~1|", subjvarname)), data=dataf, weights=varident(form = as.formula(paste("~1|", visitvarname))))) mlist }
Comments
Post a Comment