有交互項的多元線性迴歸

dom

若兩個預測變量的交互項顯著,說明響應變量與其中一個預測變量的關係依賴與另一個預測變量的水平函數

#以mtcars數據框中的汽車數據爲例,查看汽車重量和馬力對mpg的影響
> fit <- lm(mpg ~ hp + wt + hp:wt, data=mtcars)
> summary(fit)

Call:
lm(formula = mpg ~ hp + wt + hp:wt, data = mtcars)  # hp:wt 表示交互項

Residuals:
    Min      1Q  Median      3Q     Max 
-3.0632 -1.6491 -0.7362  1.4211  4.5513 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 49.80842    3.60516  13.816 5.01e-14 ***
hp          -0.12010    0.02470  -4.863 4.04e-05 ***
wt          -8.21662    1.26971  -6.471 5.20e-07 ***
hp:wt        0.02785    0.00742   3.753 0.000811 *** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.153 on 28 degrees of freedom
Multiple R-squared:  0.8848,	Adjusted R-squared:  0.8724 
F-statistic: 71.66 on 3 and 28 DF,  p-value: 2.981e-13
  • effect()

effect包中effect()函數,能夠用圖形展現交互項的結果,格式爲spa

plot(effect(term,mod,xlevels),mutilline = TRUE)

term:模型都要畫的項code

mod:爲經過lm()擬合的模型orm

xlevels:是一個列表,指定變量要設定的常量值ip

multiline:=TRUE選項表示添加相應的直線ci

it

#將上述例子中wt的值設置爲2.2,3.2,4.2擬合成直線
> library(effects)
#Warning message:
#程輯包‘effects’是用R版本3.4.1 來建造的 
> plot(effect("hp:wt", fit,, list(wt=c(2.2, 3.2, 4.2))), multiline=TRUE)

 

相關文章
相關標籤/搜索