使用 R 中的交互项进行线性回归预测

Linear regression prediction using interaction terms in R

我正在尝试编写一个使用交互项的模型,并使用该模型生成样本外预测。

我的训练样本有 3 个变量和 11 行。 我的测试样本有 3 个变量和 1 行。

我的代码如下。

inter.model <- lm(Y.train ~ Y.lag.train +  X.1.train + X.1.train:X.2.train)

但是,我不太确定 R 是如何处理交互项的。 我使用模型和测试数据的系数对预测进行了编码。

inter.prediction <- inter.model$coef[1] + inter.model$coef[2]*Y.lag.test + 
        inter.model$coef[3]*X.1.test + (inter.model$coef[4]*X.1.test*X.2.test)

我想确保这些预测被正确编码。因此,我尝试用 R 的预测函数生成它们。

inter.pred.function <- predict(inter.model, newdata=test_data)

但是,我收到一条错误消息:

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
  variable lengths differ (found for 'X.2.train')
In addition: Warning message:
'newdata' had 1 row but variables found have 11 rows 
names(test_data)
[1] "Y.lag.test" "X.1.test" "X.1.test:X.2.test"

所以,我的问题是,您如何使用 R 中的交互项进行编码和线性回归预测?

您的新数据中不需要 "X.1.test:X.2.test",交互是通过 model.matrixstats:::predict.lm 中自动创建的。

fit <- lm(mpg ~ hp*am, mtcars[1:10, ])

test <- mtcars[-(1:10), c('mpg', 'hp', 'am')]

as.numeric(predict(fit, newdata=test))
# [1] 20.220513 17.430053 17.430053 17.430053 16.206167 15.716612 14.982281 25.658824 27.141176 25.764706
# [11] 21.493355 18.898716 18.898716 14.247949 17.674830 25.658824 23.011765 20.682353  4.694118 14.117647
# [21] -2.823529 21.105882