建立交互作用的模型
在這個練習中,你會用交互作用來建模性別與胃部活性對酒精代謝的影響。
alcohol 資料框已經載入,包含以下欄位:
Metabol:酒精代謝速率Gastric:胃部酒精去氫酶活性速率Sex:飲酒者的性別(Male或Female)
在影片中,我們對 alcohol 資料擬合了 3 個模型:
- 只有加性(主效應)項的模型:
Metabol ~ Gastric + Sex - 兩個包含胃部活性與性別之交互作用的模型
你會看到,其中一個包含交互作用項的模型有比加性模型更好的 R-squared,表示加入交互作用能得到更好的擬合。 在本練習中,你會比較其中一個交互作用模型與只含主效應模型的 R-squared。
回想一下,運算子 : 代表兩個變數之間的交互作用。運算子 * 則代表兩個變數的主效應加上它們的交互作用。
x*y = x + y + x:y
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 寫出一個不含交互作用、以
Gastric和Sex解釋Metabol的公式。- 把公式指定給變數
fmla_add,並印出它。
- 把公式指定給變數
- 寫出一個以
Gastric與Sex的交互作用解釋Metabol的公式。- 加入
Gastric作為主效應,但不要加入Sex。 - 把公式指定給變數
fmla_interaction,並印出它。
- 加入
- 以只有主效應的公式對資料擬合線性模型:
model_add。 - 以交互作用的公式對資料擬合線性模型:
model_interaction。 - 對兩個模型都呼叫
summary()。哪一個的 R-squared 較好?
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# alcohol is available
summary(alcohol)
# Create the formula with main effects only
(fmla_add <- ___ )
# Create the formula with interactions
(fmla_interaction <- ___ )
# Fit the main effects only model
model_add <- ___
# Fit the interaction model
model_interaction <- ___
# Call summary on both models and compare
___
___