如何从R lme对象中提取特定组的随机效果?

时间:2010-09-10 11:43:37

标签: r

我已经成功地拟合了线性混合效应模型,我正在寻找为各个组提取随机效应组件。我知道可以使用

提取完整的随机效果列表
random.effects(model)

然后print(random.effects(model))给出一个两列的组名和随机效果列表,即使数据本身看起来只有一列。我的问题是,是否可以通过组名称“查找”与特定组关联的随机效果,或者,如果不是,我可以按照与数据中的随机效果相同的顺序查找组名列表random.effects()输出的帧。

谢谢你,Mark Ch。

3 个答案:

答案 0 :(得分:1)

这是你要找的吗?

> library(nlme)    
> fm1 <- nlme(height ~ SSasymp(age, Asym, R0, lrc),
            data = Loblolly,
            fixed = Asym + R0 + lrc ~ 1,
            random = Asym ~ 1,
            start = c(Asym = 103, R0 = -8.5, lrc = -3.3))

> str(random.effects(fm1))
Classes ‘ranef.lme’ and 'data.frame':   14 obs. of  1 variable:
 $ Asym: num  -5.57 -5.02 -1.69 -2.36 -2.98 ...
 - attr(*, "effectNames")= chr "Asym"
 - attr(*, "label")= chr "Random effects"
 - attr(*, "level")= int 1
 - attr(*, "standardized")= logi FALSE
 - attr(*, "grpNames")= chr "Seed"
> random.effects(fm1)$Asym
 [1] -5.5654676 -5.0168202 -1.6920794 -2.3587798 -2.9814647 -1.4018554
 [7] -0.1100587 -2.3613150  1.1947892  2.0119121  2.9862349  3.5890462
[13]  4.6094776  7.0963810

答案 1 :(得分:1)

事实证明,问题是我对群组编制索引的特殊方式。 ranef(lme)返回一个数据框,其中行名称是组名。在我的数据中,我使用了一个很长的数字来区分组,其中R舍入到少数小数位。这意味着无法按名称准确引用各个群体。

我通过将每个索引转换为base-62数字来解决问题。我使用数字和小写和大写字母作为数字中的字符集。 (也就是说,匹配的数字为[a-zA-Z0-9] *)这大大缩短了组名的长度,使得R无法围绕组名称 - 你使用的字符越多,得到的字符越短

现在,如果我这样做:

M3.ranef <- ranef(M3)
x <- M3.ranef[group_ID,1]

x是名为group_ID的组的随机效应,这是数据帧的工作方式。

答案 2 :(得分:0)

> library(nlme)
> d <- data.frame(x=rep(letters, each=5),
                z=rep(LETTERS[1:13], each=10),
                y=rep(rnorm(26, sd=2), each=5) + rep(rnorm(13), each=10) + rnorm(26 * 5))
> r <- ranef(d)   # random.effects is a synonym for this
# Look at the structure of r
> str(r)
List of 2
 $ z:'data.frame':  13 obs. of  1 variable:
  ..$ (Intercept): num [1:13] -1.575 -0.365 -1.817 0.235 2.369 ...
  ..- attr(*, "effectNames")= chr "(Intercept)"
 $ x:'data.frame':  26 obs. of  1 variable:
  ..$ (Intercept): num [1:26] -0.8628 0.0536 1.724 -1.9115 -1.1764 ...
  ..- attr(*, "effectNames")= chr "(Intercept)"
 - attr(*, "label")= chr "Random effects"
 - attr(*, "level")= int 2
 - attr(*, "standardized")= logi FALSE
 - attr(*, "grpNames")= chr [1:2] "z" "x %in% z"
 - attr(*, "class")= chr [1:2] "ranef.lme" "list"
> head(r$x)
    (Intercept)
A/a -0.86283867
A/b  0.05360748
B/c  1.72401850
B/d -1.91145501
C/e -1.17643222
C/f  0.24315559
> head(r$z)
  (Intercept)
A  -1.5752441
B  -0.3648627
C  -1.8167101
D   0.2353324
E   2.3685118
F  -1.7544619
> r$z["A", ]
[1] -1.575244
> r$x["A/a", ]
[1] -0.8628387