将R中的线性模型拟合为各种值

时间:2020-06-05 04:34:09

标签: r linear-regression anova oneway

在该实验中,对动物尝试了四种不同的饮食。然后研究人员测量了它们对凝血时间的影响。

 ## 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中使用函数lm来拟合coag〜diet的线性模型 结果应如下所示:

> 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)

3 个答案:

答案 0 :(得分:2)

"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)。

答案 1 :(得分: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

答案 2 :(得分:1)

您也可以考虑以这种方式编码def maxContiguousFragment(arr): b = max(arr) s = 0 for i in arr: s = max(s + i, i) b = max(s, b) return b def max_K_Subarray(arr,k): return max(maxContiguousFragment( arr[i:i+k] for i in range(len(arr)-k)))

diet
相关问题