data(mtcars)
View(mtcars)
str(mtcars)
## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
miles_per_gallon <- mtcars[,1]
cylinder <- mtcars$cyl
model1 <- lm(miles_per_gallon ~cylinder)
model1
##
## Call:
## lm(formula = miles_per_gallon ~ cylinder)
##
## Coefficients:
## (Intercept) cylinder
## 37.885 -2.876
Given sample used, If a car ran hypothetically with no cylinder, it would give 37.885 miles_per_gallon of gasoline it uses. With each cylinder more in the car as, its mileage will decrease 2.876miles_per_gallon.
A car with 8 cylinders will have a predicted mileage of ?
predict(model1, newdata=data.frame(cylinder=8))
## 1
## 14.87826
Therefore a car with 8 cylinder will have predicted mileage of 14.87826 miles_per_gallon.
A car with 6 cylinders will have a predicted mileage of ?
predict(model1, newdata=data.frame(cylinder=6))
## 1
## 20.62984
Therefore a car with 6 cylinder will have predicted mileage of 20.62984 miles_per_gallon.
A car with 4 cylinders will have a predicted mileage of ?
predict(model1, newdata=data.frame(cylinder=4))
## 1
## 26.38142
Therefore a car with 4 cylinder will have predicted mileage of 26.38142 miles_per_gallon.
plot <- plot(cylinder,miles_per_gallon,type = "p",main = "Gas consumption as explained by number of cylinders",
sub ="General Information", xlab = "# of cylinders", ylab ="Miles (US) per gallon",col="firebrick" )
abline(model1)
variables to be used mpg,cyl, am
am <- mtcars$am
model2 <- lm(miles_per_gallon~cylinder+ am)
model2
##
## Call:
## lm(formula = miles_per_gallon ~ cylinder + am)
##
## Coefficients:
## (Intercept) cylinder am
## 34.522 -2.501 2.567
In this model,along with the number of cylinders, we include the variable am(0 if the car has automatic transmission, 1 if is manual) 1.If the car is automatic and the number of cylinders is 0, the hypothetical mileage of it would be 34.522 miles_per_gallon. 2.If everything else remain constant, per each cylinder more than the car has, it will decrease by 2.501miles_per_gallon. 3.If everything else remain constant, If the car is manual, its mileage will increase by 2.567 miles_per_gallon.