I()的功能是什么?

时间:2013-02-27 14:28:45

标签: r regression linear-regression

我在互联网上找到了以下代码

mod1 <- lm(mpg ~ weight + I(weight^2) + foreign, auto)

功能I()是什么?似乎weight^2的结果与I(weight^2)相同。

1 个答案:

答案 0 :(得分:12)

I()的功能是在公式中隔离术语与通常的公式解析&amp;句法。 I()在数据框中还有其他用途,它可以帮助创建具有或继承自类"AsIs"的对象,这些对象允许嵌入对象而不进行通常的转换。

在公式的情况下,正如您特别询问的那样,^是一个特殊的公式运算符,它表示将术语交叉到n度,n给出^n跟随运算符如下:^。因此-在公式中没有通常的算术解释。 (同样,+/*I()运算符也有特殊的公式含义,因此trees需要使用它们来隔离它们从公式解析工具。)

在您给出的具体示例中(我将使用内置数据集I()来说明),如果您忘记使用Volume围绕二次项,R将在此例如,完全忽略该术语weight(示例中为I())已经在模型中,并且您要求变量与其自身的多向交互,这不是二次项。< / p>

首先没有> lm(Height ~ Volume + Volume^2, data = trees) Call: lm(formula = Height ~ Volume + Volume^2, data = trees) Coefficients: (Intercept) Volume 69.0034 0.2319

Volume

请注意公式中只有> lm(Height ~ Volume + I(Volume^2), data = trees) Call: lm(formula = Height ~ Volume + I(Volume^2), data = trees) Coefficients: (Intercept) Volume I(Volume^2) 65.33587 0.47540 -0.00314 项?二次模型的正确规范(实际上可能不是,见下文)是

Volume

我说这可能不正确;这是因为. An identical but more stable fit can be achieved by the use of orthogonal polynomials, which和Volume ^ 2之间的相关性> lm(Height ~ poly(Volume, 2), data = trees) Call: lm(formula = Height ~ poly(Volume, 2), data = trees) Coefficients: (Intercept) poly(Volume, 2)1 poly(Volume, 2)2 76.000 20.879 -5.278 poly()`可以为你生成。因此,更稳定的选择将是:

summary()

注意,拟合与早期模型相同,但由于输入数据不同(正交多项式与原始多项式),因此具有不同的系数估计。如果你不相信我,你可以通过> summary(lm(Height ~ poly(Volume, 2), data = trees)) Call: lm(formula = Height ~ poly(Volume, 2), data = trees) Residuals: Min 1Q Median 3Q Max -11.2266 -3.6728 -0.0745 2.4073 9.9954 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 76.0000 0.9322 81.531 < 2e-16 *** poly(Volume, 2)1 20.8788 5.1900 4.023 0.000395 *** poly(Volume, 2)2 -5.2780 5.1900 -1.017 0.317880 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 5.19 on 28 degrees of freedom Multiple R-squared: 0.3808, Adjusted R-squared: 0.3365 F-statistic: 8.609 on 2 and 28 DF, p-value: 0.001219 > summary(lm(Height ~ Volume + I(Volume^2), data = trees)) Call: lm(formula = Height ~ Volume + I(Volume^2), data = trees) Residuals: Min 1Q Median 3Q Max -11.2266 -3.6728 -0.0745 2.4073 9.9954 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 65.335867 4.110886 15.893 1.52e-15 *** Volume 0.475398 0.246279 1.930 0.0638 . I(Volume^2) -0.003140 0.003087 -1.017 0.3179 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 5.19 on 28 degrees of freedom Multiple R-squared: 0.3808, Adjusted R-squared: 0.3365 F-statistic: 8.609 on 2 and 28 DF, p-value: 0.001219 输出看到这个:

^

注意 t 中的差异 - 测试模型中的线性和二次项。这是输入多项式项的正交性有帮助的地方。

要真正了解?formula在公式中的作用(如果> lm(Height ~ (Girth + Volume)^2, data = trees) Call: lm(formula = Height ~ (Girth + Volume)^2, data = trees) Coefficients: (Intercept) Girth Volume Girth:Volume 75.40148 -2.29632 1.86095 -0.05608 中的术语不是您熟悉的,请考虑以下模型:

(...)^2

由于Height ~ Girth * Volume中有两个术语,公式解析代码会将其转换为两个变量的主效果及其二阶交互。该模型可以更简洁地编写为^,但{{1}}可以帮助您在大量变量之间进行高阶交互或交互。