【问题标题】:Using predict() with an interaction term between categorical variable and square root transform variable使用 predict() 与分类变量和平方根变换变量之间的交互项
【发布时间】:2017-05-12 00:35:10
【问题描述】:

我正在尝试使用 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

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

【问题讨论】:

  • 您的新数据框没有 cyl 列。尝试添加。
  • @ahly 好的,这似乎已经解决了。谢谢!

标签: r regression transformation categorical-data interaction


【解决方案1】:

在进行预测时,您需要模型中使用的所有输入,否则无法进行预测。由于您有交互,因此对于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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多