Extract random effect variances from lme4 mer model object

后端 未结 6 1570

I have a mer object that has fixed and random effects. How do I extract the variance estimates for the random effects? Here is a simplified version of my question.

6条回答
  •  醉话见心
    2020-12-24 01:52

    Some of the other answers are workable, but I claim that the best answer is to use the accessor method that is designed for this -- VarCorr (this is the same as in lme4's predecessor, the nlme package).

    UPDATE in recent versions of lme4 (version 1.1-7, but everything below is probably applicable to versions >= 1.0), VarCorr is more flexible than before, and should do everything you want without ever resorting to fishing around inside the fitted model object.

    library(lme4)
    study <- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy)
    VarCorr(study)
    ##  Groups   Name        Std.Dev.
    ##  Subject  (Intercept) 37.124  
    ##  Residual             30.991
    

    By default VarCorr() prints standard deviations, but you can get variances instead if you prefer:

    print(VarCorr(study),comp="Variance")
    ##  Groups   Name        Variance
    ##  Subject  (Intercept) 1378.18 
    ##  Residual              960.46 
    

    (comp=c("Variance","Std.Dev.") will print both).

    For more flexibility, you can use the as.data.frame method to convert the VarCorr object, which gives the grouping variable, effect variable(s), and the variance/covariance or standard deviation/correlations:

    as.data.frame(VarCorr(study))
    ##        grp        var1 var2      vcov    sdcor
    ## 1  Subject (Intercept)  1378.1785 37.12383
    ## 2 Residual           960.4566 30.99123
    

    Finally, the raw form of the VarCorr object (which you probably shouldn't mess with you if you don't have to) is a list of variance-covariance matrices with additional (redundant) information encoding the standard deviations and correlations, as well as attributes ("sc") giving the residual standard deviation and specifying whether the model has an estimated scale parameter ("useSc").

    unclass(VarCorr(fm1))
    ## $Subject
    ##             (Intercept)      Days
    ## (Intercept)  612.089748  9.604335
    ## Days           9.604335 35.071662
    ## attr(,"stddev")
    ## (Intercept)        Days 
    ##   24.740448    5.922133 
    ## attr(,"correlation")
    ##             (Intercept)       Days
    ## (Intercept)  1.00000000 0.06555134
    ## Days         0.06555134 1.00000000
    ## 
    ## attr(,"sc")
    ## [1] 25.59182
    ## attr(,"useSc")
    ## [1] TRUE
    ## 
    

提交回复
热议问题