[英]Fit linear model in R for various values
在這個實驗中,在動物身上嘗試了四種不同的飲食。 然后研究人員測量了它們對血液凝固時間的影響。
## Data :
coag diet
1 62 A
2 60 A
3 63 A
4 59 A
5 63 B
6 67 B
7 71 B
8 64 B
9 65 B
10 66 B
11 68 C
12 66 C
13 71 C
14 67 C
15 68 C
16 68 C
17 56 D
18 62 D
19 60 D
20 61 D
21 63 D
22 64 D
23 63 D
24 59 D
我正在嘗試通過在 R 中使用 function lm 來為 coag~diet 擬合線性 model 結果應如下所示:
> modelSummary$coefficients
Estimate Std. Error t value Pr(>|t|)
(Intercept) 6.100000e+01 1.183216 5.155441e+01 9.547815e-23
dietB 5.000000e+00 1.527525 3.273268e+00 3.802505e-03
dietC 7.000000e+00 1.527525 4.582576e+00 1.805132e-04
dietD -1.071287e-14 1.449138 -7.392579e-15 1.000000e+00
到目前為止,我的代碼看起來不像結果:
coagulation$x1 <- 1*(coagulation$diet=="B")
coagulation$x2 <- 1*(coagulation$diet=="C")
coagulation$x3 <- 1*(coagulation$diet=="D")
modelSummary <- lm(coag~1+x1+x2+x3, data=coagulation)
"diet"
是一個字符變量,被視為一個因素。 因此,您可以省略虛擬編碼,只需執行以下操作:
summary(lm(coag ~ diet, data=coagulation))$coefficients
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 6.100000e+01 1.183216 5.155441e+01 9.547815e-23
# dietB 5.000000e+00 1.527525 3.273268e+00 3.802505e-03
# dietC 7.000000e+00 1.527525 4.582576e+00 1.805132e-04
# dietD 2.991428e-15 1.449138 2.064281e-15 1.000000e+00
即使"diet"
是一個數字變量,並且您希望 R 將其視為分類變量而不是連續變量,也不需要虛擬編碼,您只需將其作為+ factor(diet)
添加到公式中。
如您所見, 1 +
也是多余的,因為lm
默認計算(Intercept)
。 要省略截距,您可以執行0 +
(或- 1
)。
該演示文稿是summary(modelSummary)
(類summary.lm
)的屬性,而不是modelSummary
(類lm
)的屬性。
summary(modelSummary)$coefficients
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 6.100000e+01 1.183216 5.155441e+01 9.547815e-23
# x1 5.000000e+00 1.527525 3.273268e+00 3.802505e-03
# x2 7.000000e+00 1.527525 4.582576e+00 1.805132e-04
# x3 2.991428e-15 1.449138 2.064281e-15 1.000000e+00
您也可以考慮以這種方式編碼diet
coagulation$diet <- factor(coagulation$diet)
modelSummary<-lm(coag~diet,coagulation)
summary(modelSummary)
Call:
lm(formula = coag ~ diet, data = coagulation)
Residuals:
Min 1Q Median 3Q Max
-5.00 -1.25 0.00 1.25 5.00
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 6.100e+01 1.183e+00 51.554 < 2e-16 ***
dietB 5.000e+00 1.528e+00 3.273 0.003803 **
dietC 7.000e+00 1.528e+00 4.583 0.000181 ***
dietD 2.991e-15 1.449e+00 0.000 1.000000
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.