2010-09-10 50 views
2

我已經成功地擬合了一個線性混合效果模型,並且我正在尋找爲各個組提取隨機效果組件。我知道的隨機效應的完整列表可使用如何從R lme對象中爲特定組提取隨機效果?

random.effects(model) 

然後打印(random.effects(型號))給出組名和隨機效應的兩列列表,即使該數據本身似乎被提取只有一列。我的問題是,是否有可能通過組名來「查找」與特定組關聯的隨機效應,或者如果不能,我如何能夠以與數據中的隨機效應相同的順序來查找組名列表由random.effects()輸出的幀。

謝謝
Mark Ch。

+1

'level'參數不起作用嗎? http://finzi.psych.upenn.edu/R/library/nlme/html/ranef.lme.html – 2010-09-10 13:28:06

+0

不,問題不在於我找不到任何隨機效果;我想要一個給定組的具體價值。我有一個功能上是隨機效應列表的數據框。當我打印時(random.effects(Model)),我得到兩列 - 右邊是組名列表,左邊是隨機效果列表。然而,random.effects(Model)[「group_name」]不起作用(但是如果我知道如何選擇一個整數i,random.effects(Model)[i]將起作用)。 R語言中的哪些內容將我在左側看到的名稱與我在右側看到的值聯繫在一起? – 2010-09-10 15:48:07

回答

1

事實證明,這個問題是我編制索引組的特殊方式。 ranef(lme)返回一個數據框,其中行名是組名。在我的數據中,我用了很長的數字來區分不同的小組,這些R小數點後幾位小數。這意味着不可能按名稱精確地引用各個組。

我通過將每個索引轉換爲基數爲62的數字來解決了這個問題。我使用數字和小寫字母和大寫字母作爲數字中的字符集。 (即匹配的數字[a-zA-Z0-9] *)這大大縮短了組名的長度,並且使R無法圍繞組名稱 - 您使用的字符越多,獲取的字符越短。現在

,如果我這樣做:

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

x是名爲GROUP_ID組,這是數據幀如何工作的隨機效應。

+0

您是否嘗試將您的groud_id轉換爲一個因子? – Thierry 2010-09-11 22:33:56

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 
+0

感謝您的幫助 - 我以前不知道如何使用str(),並且最終索引的方式基本上是我需要的。該索引不起作用的原因我在我的答案中指出。 – 2010-09-10 21:42:59

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