2014-02-10 36 views
1

我試圖符合以下模型提供一個均值爲中心的變量:如何在迴歸模型

enter image description here

使用lm在R.

我不能讓我的頭圍繞以下行爲...

library(nlme) 
library(plyr) 
#create toy data set 
df0<-Orthodont 
df0<-ddply(df0, .(Subject), mutate, lag1=c(NA,distance[1:(length(distance)-1)])) 
df0<-subset(df0, !is.na(lag1)) 
head(df0) 
# distance age Subject Sex lag1 
# 2  21.5 10  M16 Male 22.0 
# 3  23.5 12  M16 Male 21.5 
# 4  25.0 14  M16 Male 23.5 
# 6  23.5 10  M05 Male 20.0 
# 7  22.5 12  M05 Male 23.5 
# 8  26.0 14  M05 Male 22.5 

lm(distance ~ 1, data=df0)$coef 
# (Intercept) 
#  24.6358 
lm(distance ~ lag1, data=df0)$coef 
# (Intercept)  lag1 
# 6.2798336 0.7866844 
lm(distance ~ I(lag1-mean(distance)), data=df0)$coef 
#    (Intercept) I(lag1 - mean(distance)) 
#    25.6604346    0.7866844 

第一個模型中的截距參數是整體平均值distance 。爲什麼當我的意思是居中滯後變量時,這不會重新出現在最終模型中?

+0

我認爲這是一個很好的問題,但它會是一個更好的問題關於交叉驗證問題。 – nograpes

回答

5

嘗試以mean(lag1)爲中心?下面是一個按預期工作的例子,但您必須以相同的自變量爲中心。

> set.seed(1) 
> df <- data.frame(x=1:10, y=1:10+runif(10)) 
> lm(y ~ x, df)$coef 
(Intercept)   x 
    0.5111385 1.0073410 
> lm(y ~ 1, df)$coef 
(Intercept) 
    6.051514 
> lm(y ~ I(x - mean(x)), df)$coef 
    (Intercept) I(x - mean(x)) 
     6.051514  1.007341 
+0

謝謝。不知道爲什麼我以前看不到它......就我的理解,我的代碼確實反映了我有頂級的模型,在那裏你的解決了我在R輸出中的困惑? – gjabel

+0

@gjabel,我的代碼只是試圖強調,只要你從變量中減去變量的平均值就可以工作。你唯一的問題是你從滯後變量中減去變量的平均值而不是滯後變量的平均值。 – BrodieG