0

I am building a linear regression model using train data and I am receiving the error: No applicable method for 'predict' applied to an object of class "summary.lm". It happens when I try to run the mutate and predict function. I have also tried adding summary(lm..) instead but that threw another error.

    jointsplit <- initial_split(jointdata, prop = 0.7)
    
    jointtrain <- training(jointsplit)
    jointtest <- testing(jointsplit)
    
    #Q3-2
    
    linearmodel <- lm(JobSatisfaction ~ JobRole + Age + BusinessTravel + Department + DistanceFromHome + Education + EducationField + Gender + JobLevel +
       + MaritalStatus + MonthlyIncome + NumCompaniesWorked + PercentSalaryHike + StockOptionLevel + TotalWorkingYears + TrainingTimesLastYear +
       YearsAtCompany + YearsSinceLastPromotion + YearsWithCurrManager + WorkLifeBalance, data = jointtrain) %>%
    summary()

jointtest <-jointtest %>% 
  mutate(predictedsatis = predict(linearmodel, newdata = jointtest))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Crystal
  • 21
  • 4
  • 1
    Leave the `summary()` part off when you create `linearmodel` You need the original model object, not the summary to make predictions. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 08 '21 at 07:07
  • Also I would make more sense (once that summary() call is removed from the creation of `linearmodel` to execute `jointtest$pred <-jointtest %>% mutate(predictedsatis = predict(linearmodel, newdata = jointtest))`. That way the predictions could be compared to individual variables. – IRTFM Dec 08 '21 at 17:29
  • I am still getting the error after removing the summary(). I will provide an example. – Crystal Dec 08 '21 at 18:10
  • My data does contain factor and numeric values. Could that be why? – Crystal Dec 08 '21 at 18:23

1 Answers1

0

You need to keep the lm() object. So if you take out %>% summary() :

linearmodel = lm(mpg ~ disp + hp, data = mtcars)
mtcars  = mtcars %>% 
mutate(predicted = predict(linearmodel, newdata = mtcars))

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb predicted
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4  23.14809
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  23.14809
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  25.14838
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1  20.17416
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2  15.46423
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1  21.29978
StupidWolf
  • 45,075
  • 17
  • 40
  • 72