Emilia Delizia
Emilia Delizia

Reputation: 343

Linear regression in R: Warning: 'newdata' had 1 row but variables found have 392 rows

I am trying to predict a single variable in R, I have tried everything but I still get no result.

I am using the Auto data and I build a model like that


my_acc<-auto_df$acceleration
my_horse<-auto_df$horsepower
mydata <- data.frame(my_acc, my_horse )
car_linear_regression <- lm(my_acc ~ my_horse, mydata )

then I go on and I want to predict the following:

What is the predicted acceleration associated with a horsepower of 93.5? What are the associated 99% confidence and prediction intervals?

I use the following code and I get a warning

Warning: 'newdata' had 1 row but variables found have 392 rows

but also prints out all the rows in the dataframe while I am suposed to get only one back.

can someone help?


predict(car_linear_regression,newdata = data.frame(horsepower = 93.5))

Upvotes: 1

Views: 618

Answers (1)

Glen
Glen

Reputation: 1772

It would help to make the example reproducible but I did some work and was able to reproduce the error:

library(ISLR)
auto_df = Auto

my_acc<-auto_df$acceleration
my_horse<-auto_df$horsepower
mydata <- data.frame(my_acc, my_horse )
car_linear_regression <- lm(my_acc ~ my_horse, mydata )

predict(car_linear_regression,newdata = data.frame(horsepower = 93.5))

The problem is in your model there is no variable called horsepower. You called it my_horse, so the following works:

predict(car_linear_regression,newdata = data.frame(my_horse = 93.5))

As a side note, instead of creating separate variables I would just call the regression model as:

car_linear_regression <- lm(acceleration ~ horsepower, data=auto_df )

Then your original prediction would have worked.

Upvotes: 2

Related Questions