Data Project 1

Author

Akeeb Haque

Introduction

This project investigates the relationship between car horsepower and highway fuel efficiency. The dataset contains 5,076 observations and 18 variables describing cars, including make, model year, fuel type, transmission, horsepower, torque, and city and highway miles per gallon (MPG).

Horsepower measures engine power, while highway MPG indicates how many miles a vehicle can travel per gallon of fuel on the highway. These variables are quantitative because they are measured numerically. Fuel type and car make are categorical variables because they identify groups.

My main research question is, “Do cars with higher horsepower tend to have lower highway fuel efficiency?” I will use summary statistics, a scatterplot, and linear regression to investigate this relationship. I will also use fuel type to distinguish groups in the visualization.

Source: https://corgis-edu.github.io/corgis/csv/cars/

# Load the libraries needed for data cleaning and visualization.
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)

# Import the car dataset from the CSV file.
cars <- read_csv("C:/Users/akeeb/Downloads/cars.csv")
Rows: 5076 Columns: 18
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (8): Engine Information.Driveline, Engine Information.Engine Type, Engin...
dbl (9): Dimensions.Height, Dimensions.Length, Dimensions.Width, Engine Info...
lgl (1): Engine Information.Hybrid

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Standardize column names so they are easier to reference in R.
names(cars) <- make.names(names(cars))

# Display the first six rows of the dataset.
head(cars)
# A tibble: 6 × 18
  Dimensions.Height Dimensions.Length Dimensions.Width Engine.Information.Driv…¹
              <dbl>             <dbl>            <dbl> <chr>                    
1               140               143              202 All-wheel drive          
2               140               143              202 Front-wheel drive        
3               140               143              202 Front-wheel drive        
4               140               143              202 All-wheel drive          
5               140               143              202 All-wheel drive          
6                91                17               62 All-wheel drive          
# ℹ abbreviated name: ¹​Engine.Information.Driveline
# ℹ 14 more variables: Engine.Information.Engine.Type <chr>,
#   Engine.Information.Hybrid <lgl>,
#   Engine.Information.Number.of.Forward.Gears <dbl>,
#   Engine.Information.Transmission <chr>, Fuel.Information.City.mpg <dbl>,
#   Fuel.Information.Fuel.Type <chr>, Fuel.Information.Highway.mpg <dbl>,
#   Identification.Classification <chr>, Identification.ID <chr>, …
# Check the column names and data types.
names(cars)
 [1] "Dimensions.Height"                              
 [2] "Dimensions.Length"                              
 [3] "Dimensions.Width"                               
 [4] "Engine.Information.Driveline"                   
 [5] "Engine.Information.Engine.Type"                 
 [6] "Engine.Information.Hybrid"                      
 [7] "Engine.Information.Number.of.Forward.Gears"     
 [8] "Engine.Information.Transmission"                
 [9] "Fuel.Information.City.mpg"                      
[10] "Fuel.Information.Fuel.Type"                     
[11] "Fuel.Information.Highway.mpg"                   
[12] "Identification.Classification"                  
[13] "Identification.ID"                              
[14] "Identification.Make"                            
[15] "Identification.Model.Year"                      
[16] "Identification.Year"                            
[17] "Engine.Information.Engine.Statistics.Horsepower"
[18] "Engine.Information.Engine.Statistics.Torque"    
str(cars)
spc_tbl_ [5,076 × 18] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ Dimensions.Height                              : num [1:5076] 140 140 140 140 140 91 91 201 201 147 ...
 $ Dimensions.Length                              : num [1:5076] 143 143 143 143 143 17 17 221 221 96 ...
 $ Dimensions.Width                               : num [1:5076] 202 202 202 202 202 62 62 191 191 34 ...
 $ Engine.Information.Driveline                   : chr [1:5076] "All-wheel drive" "Front-wheel drive" "Front-wheel drive" "All-wheel drive" ...
 $ Engine.Information.Engine.Type                 : chr [1:5076] "Audi 3.2L 6 cylinder 250hp 236ft-lbs" "Audi 2.0L 4 cylinder 200 hp 207 ft-lbs Turbo" "Audi 2.0L 4 cylinder 200 hp 207 ft-lbs Turbo" "Audi 2.0L 4 cylinder 200 hp 207 ft-lbs Turbo" ...
 $ Engine.Information.Hybrid                      : logi [1:5076] TRUE TRUE TRUE TRUE TRUE TRUE ...
 $ Engine.Information.Number.of.Forward.Gears     : num [1:5076] 6 6 6 6 6 6 6 6 6 6 ...
 $ Engine.Information.Transmission                : chr [1:5076] "6 Speed Automatic Select Shift" "6 Speed Automatic Select Shift" "6 Speed Manual" "6 Speed Automatic Select Shift" ...
 $ Fuel.Information.City.mpg                      : num [1:5076] 18 22 21 21 21 16 17 13 14 22 ...
 $ Fuel.Information.Fuel.Type                     : chr [1:5076] "Gasoline" "Gasoline" "Gasoline" "Gasoline" ...
 $ Fuel.Information.Highway.mpg                   : num [1:5076] 25 28 30 28 28 27 26 18 20 30 ...
 $ Identification.Classification                  : chr [1:5076] "Automatic transmission" "Automatic transmission" "Manual transmission" "Automatic transmission" ...
 $ Identification.ID                              : chr [1:5076] "2009 Audi A3 3.2" "2009 Audi A3 2.0 T AT" "2009 Audi A3 2.0 T" "2009 Audi A3 2.0 T Quattro" ...
 $ Identification.Make                            : chr [1:5076] "Audi" "Audi" "Audi" "Audi" ...
 $ Identification.Model.Year                      : chr [1:5076] "2009 Audi A3" "2009 Audi A3" "2009 Audi A3" "2009 Audi A3" ...
 $ Identification.Year                            : num [1:5076] 2009 2009 2009 2009 2009 ...
 $ Engine.Information.Engine.Statistics.Horsepower: num [1:5076] 250 200 200 200 200 265 265 350 280 211 ...
 $ Engine.Information.Engine.Statistics.Torque    : num [1:5076] 236 207 207 207 207 243 243 325 266 258 ...
 - attr(*, "spec")=
  .. cols(
  ..   Dimensions.Height = col_double(),
  ..   Dimensions.Length = col_double(),
  ..   Dimensions.Width = col_double(),
  ..   `Engine Information.Driveline` = col_character(),
  ..   `Engine Information.Engine Type` = col_character(),
  ..   `Engine Information.Hybrid` = col_logical(),
  ..   `Engine Information.Number of Forward Gears` = col_double(),
  ..   `Engine Information.Transmission` = col_character(),
  ..   `Fuel Information.City mpg` = col_double(),
  ..   `Fuel Information.Fuel Type` = col_character(),
  ..   `Fuel Information.Highway mpg` = col_double(),
  ..   Identification.Classification = col_character(),
  ..   Identification.ID = col_character(),
  ..   Identification.Make = col_character(),
  ..   `Identification.Model Year` = col_character(),
  ..   Identification.Year = col_double(),
  ..   `Engine Information.Engine Statistics.Horsepower` = col_double(),
  ..   `Engine Information.Engine Statistics.Torque` = col_double()
  .. )
 - attr(*, "problems")=<pointer: 0x0000020de18fd7a0> 
# Rename the columns used in the project.
cars <- cars %>%
  rename(
    make = Identification.Make,
    year = Identification.Year,
    fuel_type = Fuel.Information.Fuel.Type,
    city_mpg = Fuel.Information.City.mpg,
    highway_mpg = Fuel.Information.Highway.mpg,
    horsepower = Engine.Information.Engine.Statistics.Horsepower,
    torque = Engine.Information.Engine.Statistics.Torque
  )

# Remove rows with missing values in the variables used for analysis.
cars <- cars %>%
  drop_na(make, year, fuel_type, city_mpg, highway_mpg, horsepower, torque)

# Display the number of rows and columns after cleaning.
dim(cars)
[1] 5076   18
# Display summary statistics for the cleaned dataset.
summary(cars)
 Dimensions.Height Dimensions.Length Dimensions.Width
 Min.   :  1.0     Min.   :  2.0     Min.   :  1     
 1st Qu.:104.0     1st Qu.: 60.0     1st Qu.: 62     
 Median :152.0     Median :128.0     Median :158     
 Mean   :145.6     Mean   :127.8     Mean   :144     
 3rd Qu.:193.0     3rd Qu.:198.0     3rd Qu.:219     
 Max.   :255.0     Max.   :255.0     Max.   :254     
 Engine.Information.Driveline Engine.Information.Engine.Type
 Length   :5076               Length   :5076                
 N.unique :   4               N.unique : 535                
 N.blank  :   0               N.blank  :   0                
 Min.nchar:  15               Min.nchar:  28                
 Max.nchar:  17               Max.nchar:  60                
                                                            
 Engine.Information.Hybrid Engine.Information.Number.of.Forward.Gears
 Mode:logical              Min.   :4.000                             
 TRUE:5076                 1st Qu.:5.000                             
                           Median :6.000                             
                           Mean   :5.519                             
                           3rd Qu.:6.000                             
                           Max.   :8.000                             
 Engine.Information.Transmission    city_mpg         fuel_type   
 Length   :5076                  Min.   : 8.00   Length   :5076  
 N.unique :  11                  1st Qu.:14.00   N.unique :   4  
 N.blank  :   0                  Median :17.00   N.blank  :   0  
 Min.nchar:  14                  Mean   :17.28   Min.nchar:   3  
 Max.nchar:  30                  3rd Qu.:20.00   Max.nchar:  22  
                                 Max.   :38.00                   
  highway_mpg     Identification.Classification Identification.ID
 Min.   : 11.00   Length   :5076                Length   :5076   
 1st Qu.: 20.00   N.unique :   2                N.unique :5030   
 Median : 24.00   N.blank  :   0                N.blank  :   0   
 Mean   : 24.13   Min.nchar:  19                Min.nchar:  12   
 3rd Qu.: 28.00   Max.nchar:  22                Max.nchar:  67   
 Max.   :223.00                                                  
        make      Identification.Model.Year      year        horsepower   
 Length   :5076   Length   :5076            Min.   :2009   Min.   :100.0  
 N.unique :  47   N.unique : 918            1st Qu.:2010   1st Qu.:190.0  
 N.blank  :   0   N.blank  :   0            Median :2011   Median :266.0  
 Min.nchar:   3   Min.nchar:  11            Mean   :2011   Mean   :270.5  
 Max.nchar:  18   Max.nchar:  48            3rd Qu.:2011   3rd Qu.:317.0  
                                            Max.   :2012   Max.   :638.0  
     torque     
 Min.   : 98.0  
 1st Qu.:187.0  
 Median :260.0  
 Mean   :272.7  
 3rd Qu.:335.0  
 Max.   :774.0  
# Examine horsepower, highway MPG, and city MPG.
summary(cars$horsepower)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  100.0   190.0   266.0   270.5   317.0   638.0 
summary(cars$highway_mpg)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  11.00   20.00   24.00   24.13   28.00  223.00 
summary(cars$city_mpg)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   8.00   14.00   17.00   17.28   20.00   38.00 
# Count the number of cars in each fuel category.
table(cars$fuel_type)

Compressed natural gas            Diesel fuel                    E85 
                     2                     27                    456 
              Gasoline 
                  4591 
# Plot horsepower against highway MPG to investigate their relationship.
# Color the points by fuel type to compare categorical groups.
# Add a meaningful title, axis labels, legend, and source caption.
# Use a custom color palette and change the default ggplot theme.

ggplot(cars, aes(x = horsepower, y = highway_mpg, color = fuel_type)) +
  geom_point(alpha = 0.6) +
  scale_color_manual(values = c(
    "Gasoline" = "#0072B2",
    "E85" = "#D55E00",
    "Diesel fuel" = "#009E73",
    "Compressed natural gas" = "#CC79A7"
  )) +
  labs(
    title = "Horsepower and Highway Fuel Efficiency",
    x = "Horsepower",
    y = "Highway Fuel Efficiency (MPG)",
    color = "Fuel Type",
    caption = "Source: Insert the original dataset source and link"
  ) +
  theme_minimal()

# Build a linear regression model predicting highway MPG using horsepower.
model <- lm(highway_mpg ~ horsepower, data = cars)

# Display the regression coefficients, p-value, and adjusted R-squared.
summary(model)

Call:
lm(formula = highway_mpg ~ horsepower, data = cars)

Residuals:
    Min      1Q  Median      3Q     Max 
-13.824  -3.026   0.198   3.243 201.170 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) 34.2220194  0.2292682  149.27   <2e-16 ***
horsepower  -0.0373255  0.0007994  -46.69   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.427 on 5074 degrees of freedom
Multiple R-squared:  0.3005,    Adjusted R-squared:  0.3004 
F-statistic:  2180 on 1 and 5074 DF,  p-value: < 2.2e-16
# Arrange the diagnostic plots in a two-by-two layout.
par(mfrow = c(2, 2))

# Check the regression model assumptions using diagnostic plots.
plot(model)

# Return the plotting layout to normal.
par(mfrow = c(1, 1))

Regression Results

The linear regression model examines whether horsepower is associated with highway fuel efficiency. The estimated regression equation is: Highway MPG = 34.222 − 0.03733 × Horsepower

The slope is approximately −0.03733, meaning that each additional unit of horsepower is associated with a predicted decrease of about 0.037 highway MPG. This describes an average relationship in the dataset, not a guaranteed change for every individual car. The p-value for horsepower is below 0.001, which is less than the significance level of 0.05. Therefore, there is strong statistical evidence of a linear association between horsepower and highway MPG. The adjusted R-squared value is approximately 0.300. This means that the model accounts for about 30% of the observed variation in highway MPG. Horsepower is related to fuel efficiency, but it does not explain all the differences between vehicles. Other factors, such as vehicle weight, engine design, and transmission, may also contribute.

Conclusion and Reflection

I began by importing the original CSV file using the readr package and examining its dimensions, column names, and data types. The dataset contained 5,076 rows and 18 variables. I used the make.names() function to standardize the column names, replacing spaces and other characters with periods so the names could be referenced more easily in R. I then renamed seven variables used in the analysis, including horsepower, highway MPG, city MPG, fuel type, and car make. I checked for missing values using is.na() and removed incomplete observations with drop_na(). However, the original dataset did not contain missing values in the selected variables, so this step did not remove any rows. Finally, I used summary statistics and frequency counts to examine the data before creating the visualization and regression model. The scatterplot compares horsepower with highway fuel efficiency, measured in miles per gallon. Each point represents a car, and its color identifies the fuel type. The linear regression results indicate a negative association, meaning that cars with higher horsepower tend to have lower highway MPG. The graph also allows comparisons between fuel types, although gasoline accounts for most observations. Compressed natural gas has only two observations, and diesel has 27, so conclusions about these smaller groups should be made cautiously. One limitation is that the model uses only horsepower to predict highway MPG. Its adjusted R-squared value of approximately 0.300 indicates that horsepower alone explains about 30% of the variation in highway fuel efficiency. I would like to investigate additional variables, such as vehicle dimensions, torque, transmission type, and fuel type, to see whether they improve the model. A multiple linear regression could examine several predictors simultaneously. I would also consider creating separate visualizations for different fuel types to make group comparisons easier. Finally, I would examine the diagnostic plots carefully because unusual observations or violations of regression assumptions could affect the reliability of the model.