如下所示,我有一个包含交互项的多元线性回归,其中一些项是因子变量(季节、月份、假日、工作日、天气)
regwithint=lm(casual~season:temp+season:month+year:temp+
month:temp+holiday:temp+weekday:hum+season+
month+holiday+weekday+weathersit+temp+windspeed
,data=training)
但是,变量temp和windspeed被转换为(temp^3)和(windspeed^2)。
查看交互项,我有temp:weekday之间的交互其中temp为temp^3, weekday为因子变量。
我知道在大多数情况下我应该使用I(temp^3),但它与因子变量配对的事实是否意味着我应该使用poly(temp,3,raw=T) ?
谢谢。
首先,让我们确定I()
可以很好地与因子变量相互作用:
data(iris)
reg <- lm(Sepal.Length~Species:I(Petal.Length^2), data=iris)
summary(reg)
Call: lm(formula = Sepal.Length ~ Species:I(Petal.Length^2), data = iris) Residuals: Min 1Q Median 3Q Max -0.87875 -0.22363 -0.00197 0.21664 1.06243 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 4.245539 0.133172 31.880 < 2e-16 *** Speciessetosa:I(Petal.Length^2) 0.341688 0.062196 5.494 1.7e-07 *** Speciesversicolor:I(Petal.Length^2) 0.092381 0.007413 12.462 < 2e-16 *** Speciesvirginica:I(Petal.Length^2) 0.075714 0.004388 17.253 < 2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.3431 on 146 degrees of freedom Multiple R-squared: 0.8318, Adjusted R-squared: 0.8284 F-statistic: 240.7 on 3 and 146 DF, p-value: < 2.2e-16
现在让我们看看你的函数是否也工作:
data(iris)
reg <- lm(Sepal.Length~Species: poly(Petal.Length,2,raw=T), data=iris)
summary(reg)
它确实(注意它的不同之处在于它也必须有低阶项):
Call: lm(formula = Sepal.Length ~ Species:poly(Petal.Length, 2, raw = T), data = iris) Residuals: Min 1Q Median 3Q Max -0.73849 -0.22814 -0.01978 0.24177 0.98833 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 1.79002 1.58957 1.126 0.2620 Speciessetosa:poly(Petal.Length, 2, raw = T)1 3.87221 2.16771 1.786 0.0762 . Speciesversicolor:poly(Petal.Length, 2, raw = T)1 1.13016 0.78109 1.447 0.1501 Speciesvirginica:poly(Petal.Length, 2, raw = T)1 0.74216 0.56640 1.310 0.1922 Speciessetosa:poly(Petal.Length, 2, raw = T)2 -1.12847 0.74087 -1.523 0.1299 Speciesversicolor:poly(Petal.Length, 2, raw = T)2 -0.03641 0.09628 -0.378 0.7059 Speciesvirginica:poly(Petal.Length, 2, raw = T)2 0.02178 0.05107 0.426 0.6705 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.3367 on 143 degrees of freedom Multiple R-squared: 0.8413, Adjusted R-squared: 0.8346 F-statistic: 126.4 on 6 and 143 DF, p-value: < 2.2e-16
那么有什么区别呢?
嗯,就像我在你的另一个问题中说的,基本上只是I()
是绝大多数R程序员在lm
和glm
方程中使用的,因为它更灵活——可以用于方程内的任何变换。
但每个人都有自己的。SO不允许基于意见的问题,所以我将把这个问题解释为"两者都有效吗?",答案是"是","为什么I()被普遍使用?",答案是"它对任何转换都是灵活的"。至于你是否应该使用它,这不是一个我们可以在SO上合法地问或回答的问题,但是你可以在程序员堆栈交换(或者他们现在叫它什么)或代码审查堆栈交换上问这个问题。