Ashlee Berry Ashlee Berry - 24 days ago 4
R Question

How to predict something in R given two specifications?

I have a very large data set. Here is an example of some of it.

Car sport SUV Wagon Minivan Pickup AWD RWD MSRP Invoice EngineSize Cylinders HP City.MPG Hwy.MPG Weight
Chevrolet Aveo 4dr 0 0 0 0 0 0 0 11690 10965 1.6 4 103 28 34 2370
Chevrolet Aveo LS 4dr hatch 0 0 0 0 0 0 0 12585 11802 1.6 4 103 28 34 2348
Chevrolet Cavalier 2dr 0 0 0 0 0 0 0 14610 13697 2.2 4 140 26 37 2617
Chevrolet Cavalier 4dr 0 0 0 0 0 0 0 14810 13884 2.2 4 140 26 37 2676
Chevrolet Cavalier LS 2dr 0 0 0 0 0 0 0 16385 15357 2.2 4 140 26 37 2617
Dodge Neon SE 4dr 0 0 0 0 0 0 0 13670 12849 2.0 4 132 29 36 2581


What I want to do is predict the horsepower of a sports car with a 3.5-liter engine. I am honestly not too sure where to start. I have made these models for finding the horsepower of a sports car.

sportFilter <- cars$sport==1
hpModelSport <- lm(cars$HP[sportFilter] ~ cars$EngineSize[sportFilter])


And this for engine size.

hpModel <- lm(HP ~ EngineSize, data = cars)


But how do I use both of these. And the engine size model is just general, how do I specify 3.5-liter?

rbm rbm
Answer

Assuming you are trying to predict HP based on EngineSize and sport you can do following:

cars <- read.table("d:/Downloads/04cars.csv", header =T, sep =",", stringsAsFactors = FALSE)
fit <- lm(HP ~ EngineSize + sport , data=cars)
vals <-  data.frame(EngineSize = 3.5, sport = 1)
predict(fit, newdata=vals)
Comments