我有一个具有固定和随机效果的mer对象。如何提取随机效应的方差估计?这是我的问题的简化版本。
study <- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy)
study
这样可以提供长输出 - 在这种情况下不会太长。无论如何,我如何明确选择
Random effects:
Groups Name Variance Std.Dev.
Subject (Intercept) 1378.18 37.124
Residual 960.46 30.991
部分输出?我想要自己的价值观。
我长期看看
str(study)
那里什么都没有!还检查了lme4包中的任何提取器功能都无济于事。请帮忙!
lmer
返回一个S4对象,所以这应该工作:
remat <- summary(study)@REmat
print(remat, quote=FALSE)
哪个印刷品:
Groups Name Variance Std.Dev.
Subject (Intercept) 1378.18 37.124
Residual 960.46 30.991
...通常,您可以查看“mer”对象的print
和summary
方法的来源:
class(study) # mer
selectMethod("print", "mer")
selectMethod("summary", "mer")
其他一些答案是可行的,但我声称最好的答案是使用专为此设计的访问器方法 - VarCorr
(这与lme4
的前身nlme
包中的相同)。
更新版本的lme4
(版本1.1-7,但下面的所有内容可能适用于版本> = 1.0),VarCorr
比以前更灵活,并且应该做你想要的一切,而不必在拟合的模型对象内钓鱼。
library(lme4)
study <- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy)
VarCorr(study)
## Groups Name Std.Dev.
## Subject (Intercept) 37.124
## Residual 30.991
默认情况下,VarCorr()
打印标准偏差,但如果您愿意,可以改为:
print(VarCorr(study),comp="Variance")
## Groups Name Variance
## Subject (Intercept) 1378.18
## Residual 960.46
(comp=c("Variance","Std.Dev.")
将打印两者)。
为了更加灵活,您可以使用as.data.frame
方法转换VarCorr
对象,该对象提供分组变量,效果变量,方差/协方差或标准偏差/相关性:
as.data.frame(VarCorr(study))
## grp var1 var2 vcov sdcor
## 1 Subject (Intercept) <NA> 1378.1785 37.12383
## 2 Residual <NA> <NA> 960.4566 30.99123
最后,VarCorr
对象的原始形式(如果你不需要,你可能不应该把它弄乱)是一个方差 - 协方差矩阵列表,其中附加(冗余)信息编码标准偏差和相关性,以及作为属性("sc"
)给出剩余标准偏差并指定模型是否具有估计的尺度参数("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
##
> attributes(summary(study))$REmat
Groups Name Variance Std.Dev.
"Subject" "(Intercept)" "1378.18" "37.124"
"Residual" "" " 960.46" "30.991"
这个答案很大程度上基于@Ben Bolker的答案,但是如果人们不熟悉这个并且想要自己的值,而不仅仅是值的打印输出(如OP似乎想要的那样),那么你可以提取如下值:
将VarCorr
对象转换为数据框。
re_dat = as.data.frame(VarCorr(study))
然后访问每个单独的值:
int_vcov = re_dat[1,'vcov']
resid_vcov = re_dat[2,'vcov']
使用此方法(在您创建的日期框架中指定行和列),您可以访问您想要的任何值。
尝试
attributes(study)
举个例子:
> women
height weight
1 58 115
2 59 117
3 60 120
4 61 123
5 62 126
6 63 129
7 64 132
8 65 135
9 66 139
10 67 142
11 68 146
12 69 150
13 70 154
14 71 159
15 72 164
> lm1 <- lm(height ~ weight, data=women)
> attributes(lm1)
$names
[1] "coefficients" "residuals" "effects" "rank"
[5] "fitted.values" "assign" "qr" "df.residual"
[9] "xlevels" "call" "terms" "model"
$class
[1] "lm"
> lm1$coefficients
(Intercept) weight
25.7234557 0.2872492
> lm1$coefficients[[1]]
[1] 25.72346
> lm1$coefficients[[2]]
[1] 0.2872492
结束。