使用lmer拟合带方差结构的混合模型遇错误,求修正方法
Hey there! The error you're hitting comes from mixing syntax between two different mixed model packages: lmer() is from the lme4 package, but varWeights() is a function from the nlme package—they don't play nicely together out of the box. R is misinterpreting your varWeights() call as the control argument for lmer(), hence the confusing error message.
Here's how to fix this properly, depending on which package you want to use:
Option 1: Use nlme::lme() (Recommended for Variance Structures)
The lme() function was designed specifically to handle mixed models with flexible variance structures, so it's the perfect fit for your goal. Here's the adjusted code:
First, install/load the nlme package if you haven't already:
install.packages("nlme") # Only run once library(nlme)
Then fit your model with the correct syntax:
# Your original data frame DTF <- data.frame(Y = rnorm(7*4, 0, 1), TIME = rep(1:7, 4), GROUP = c(rep(1,7), rep(2,7), rep(3,7), rep(4,7)), X = rep(rnorm(7, 20, 5), 4)) # Fitted model with variance structure model <- lme( Y ~ TIME:GROUP + X, random = ~1 | GROUP, # Same as (1 | GROUP) in lmer() data = DTF, method = "ML", # Equivalent to REML = FALSE in lmer() weights = varFixed(~ TIME) # Specify your time-dependent variance structure )
Key Notes:
random = ~1 | GROUPreplaces the(1 | GROUP)syntax from lmer()method = "ML"matches your originalREML = FALSE; usemethod = "REML"if you want restricted maximum likelihood insteadweights = varFixed(~ TIME)directly implements the variance structure you were targeting withvarWeights()
Option 2: Stick with lme4 Ecosystem via glmmTMB
If you prefer to stay in the lme4-style syntax, the glmmTMB package supports heteroscedastic (non-constant variance) mixed models. Here's how to use it:
install.packages("glmmTMB") # Only run once library(glmmTMB) model <- glmmTMB( Y ~ TIME:GROUP + X + (1 | GROUP), data = DTF, REML = FALSE, dispformula = ~ TIME # Define variance structure here )
The dispformula argument lets you specify how the residual variance varies with your TIME variable, which achieves the same goal as your original varWeights() call.
内容的提问来源于stack exchange,提问作者Emiliano Traini

