将 predict() 与分类变量和平方根变换变量之间的交互项一起使用

Using predict() with an interaction term between categorical variable and square root transform variable

我正在尝试使用 predict() 来预测响应变量的值。我的回归包括一个分类变量和一个转换变量(平方根转换)之间的单个交互项。我使用了下面的 mtcars 数据集来确保该示例是可重现的,并且我对其进行了注释以便您了解我的想法。

attach(mtcars)
#take square root of weight
sqrt_wt = sqrt(wt)
#create new data frame from desired variables
df=data.frame(sqrt_wt,mpg,cyl)
#eliminate NAs caused by square root transformation
df1=df[complete.cases(df),]
#fit a regression with an interaction term (square root of weight vs.   number of cylinders as a factor)
fit1=lm(mpg~as.factor(cyl)*sqrt_wt,data=df1)
#create data frame of desired inputs for sqrt_wt
new.cars <- data.frame(sqrt_wt=c(1.7, 2.4))
#try to predict
predict(fit1,new.cars)

但是我得到了这个错误。

#Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
#variable lengths differ (found for 'sqrt_wt')
#In addition: Warning message:#  'newdata' had 2 rows but variables found have 32 rows

有什么想法吗?任何帮助将不胜感激。

进行预测时,您需要模型中使用的所有输入,否则无法进行预测。由于您有互动,预测将针对 cylsqrt_wt 的每个组合发生变化。在您的代码中,看起来您指定的两个值都是 sqrt_wt 并且您缺少同伴 cyl.

View(new.cars)

只需在您的测试集中包含一个 cyl。您可以在测试集中添加任意数量的观察值。考虑您感兴趣的 sqrt_wtcyl 的所有组合。

new.car <- data.frame(sqrt_wt = 1.7, cyl = 6)
predict(fit1,new.car)