在为我创建的模型预测变量时,如何将cut集成到dictate中

问题描述

R编程::我想使用ISLR库来预测某人在35岁时的工资,并假设该模型使用的值为0、35、45, 55、65、80,将变量“年龄”切成不同的括号。话虽这么说,在考虑了cut()和我的模型的情况下,predict()代码应如何?

到目前为止,这是我的代码在predict()之前:

table(cut(age,breaks = c(0,35,45,55,65,80))) # cut()

getfit.1 = lm(wage~education+cut(age,25,80)),data=Wage) # model with cut()

解决方法

如果创建分类变量然后使用它来拟合模型,将会使您的生活更轻松:

library(ISLR)
agecat <- cut(Wage$age,breaks = c(0,25,35,45,55,80))
getfit.1 <-  lm(wage~education+agecat,data=Wage)
predict(getfit.1,data.frame(education="2. HS Grad",agecat="(25,35]"))
#        1 
# 88.56445 

请注意,您还必须指定教育类别才能获得预测。因此,获得所有组合可能会很有用:

cross <- expand.grid(agecat=levels(agecat),education=levels(Wage$education))
predictions <- data.frame(cross,pwage=predict(getfit.1,cross))
head(predictions)
#    agecat    education    pwage
# 1  (0,25] 1. < HS Grad 59.12711
# 2 (25,35] 1. < HS Grad 77.65516
# 3 (35,45] 1. < HS Grad 91.86200
# 4 (45,55] 1. < HS Grad 90.84853
# 5 (55,80] 1. < HS Grad 88.53072
# 6  (0,25]   2. HS Grad 70.03640