Exploring Engine Characteristics and Vehicle Fuel Efficiency Using Tidyverse

Author

Ozge Gundogan

Published

November 30, 2026

1. Introduction

This vignette extends Patricio Romero’s original work, “Exploring Vehicle Fuel Efficiency with Tidyverse.” The original vignette focused on comparing fuel efficiency across vehicle classes and examining the relationship between city and highway fuel efficiency.

In this extension, I will use the same mpg dataset to investigate how engine displacement, number of cylinders, transmission type, and drivetrain are associated with highway fuel efficiency. The main objective is to extend the original analysis by introducing additional data transformation, statistical analysis, and visualization techniques using Tidyverse packages, including dplyr, stringr, forcats, and ggplot2.

The following research questions will guide this analysis:

1. What is the relationship between engine displacement and highway fuel efficiency?
2. How does highway fuel efficiency vary by the number of cylinders?
3. How does highway fuel efficiency differ between automatic and manual transmission vehicles?
4. How does highway fuel efficiency vary across different drivetrain types?

2. Planned Approach

First, I will load the mpg dataset and examine its structure, variables, and missing values. I will select the relevant variables and transform the transmission and drivetrain categories into more meaningful groups.

Next, I will examine the relationship between engine displacement and highway fuel efficiency using correlation analysis and a scatter plot with a regression trend line. I will also calculate summary statistics to compare fuel efficiency across different cylinder numbers, transmission types, and drivetrain categories. I plan to use different visualization techniques, including boxplots, violin plots, and bar charts, to better understand the distributions and differences between vehicle categories.

Finally, I will interpret the results, discuss the limitations of the analysis, and explain how the additional Tidyverse functions and techniques extend the original vignette.

3. Anticipated Challenges

One potential challenge is transforming the transmission and drivetrain variables into meaningful categories. Differences in group sizes may also make comparisons more difficult. Additionally, vehicle characteristics may be related to each other, making it difficult to determine their individual effects on fuel efficiency. I will carefully interpret the results and avoid making unsupported causal claims.

4. Code Base

4.1 Load Packages

I will use dplyr for data manipulation and summarization, stringr for text processing, forcats for categorical data management, and ggplot2 for data visualization.

library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(stringr)
library(forcats)
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.6.2
library(knitr)

4.2 Load the Dataset

I will use the same mpg dataset as the original vignette. The dataset contains fuel economy information for 234 vehicle configurations from the 1999 and 2008 model years. The data was originally collected by the U.S. Environmental Protection Agency (EPA).

vehicles <- ggplot2::mpg

glimpse(vehicles)
Rows: 234
Columns: 11
$ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi", "…
$ model        <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro", "…
$ displ        <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0, 2.…
$ year         <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, 200…
$ cyl          <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, …
$ trans        <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "auto…
$ drv          <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "4", "4…
$ cty          <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17, 1…
$ hwy          <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25, 2…
$ fl           <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p…
$ class        <chr> "compact", "compact", "compact", "compact", "compact", "c…

The dataset contains 234 observations and 11 variables, including both numerical and categorical variables. It includes vehicle configurations from the 1999 and 2008 model years. The main variables for this extension are engine displacement (displ), number of cylinders (cyl), transmission type (trans), drivetrain (drv), and highway fuel efficiency (hwy). These variables will help us examine the relationship between vehicle characteristics and fuel efficiency.

4.3 Dataset Overview

I will check the number of observations and variables to understand the size of the dataset.

dataset_summary <- tibble(
  Description = c("Total Vehicle Records", "Total Variables"),
  Count = c(nrow(vehicles), ncol(vehicles))
)

kable(dataset_summary, caption = "Vehicle Dataset Overview")
Vehicle Dataset Overview
Description Count
Total Vehicle Records 234
Total Variables 11

The dataset overview confirms that all 234 vehicle records and 11 variables were successfully loaded.

4.4 Data Cleaning and Transformation

4.4.1 Select Relevant Variables

I will use select() to keep the variables needed for this extension. Unlike the original vignette, this analysis includes engine displacement, transmission type, and drivetrain to explore additional factors associated with vehicle fuel efficiency.

vehicles_selected <- vehicles %>%
  select(manufacturer, model, year, displ, cyl,
         trans, drv, cty, hwy, class)

head(vehicles_selected)
# A tibble: 6 × 10
  manufacturer model  year displ   cyl trans      drv     cty   hwy class  
  <chr>        <chr> <int> <dbl> <int> <chr>      <chr> <int> <int> <chr>  
1 audi         a4     1999   1.8     4 auto(l5)   f        18    29 compact
2 audi         a4     1999   1.8     4 manual(m5) f        21    29 compact
3 audi         a4     2008   2       4 manual(m6) f        20    31 compact
4 audi         a4     2008   2       4 auto(av)   f        21    30 compact
5 audi         a4     1999   2.8     6 auto(l5)   f        16    26 compact
6 audi         a4     1999   2.8     6 manual(m5) f        18    26 compact

The selected dataset contains 10 variables, including the main characteristics needed for the following analyses.

4.4.2 Check Missing Values

I will use summarise() and across() to check for missing values in each selected variable. This step will help determine whether additional data cleaning is necessary.

missing_values <- vehicles_selected %>%
  summarise(across(everything(), ~sum(is.na(.))))

kable(missing_values, caption = "Missing Values by Variable")
Missing Values by Variable
manufacturer model year displ cyl trans drv cty hwy class
0 0 0 0 0 0 0 0 0 0

The results show that none of the 10 selected variables contain missing values. Therefore, no missing value imputation or row removal is necessary. All 234 observations can be retained for further analysis.

4.4.3 Check Unique Categories

Before transforming the categorical variables, I will use distinct() and arrange() to identify the existing transmission and drivetrain categories.

Identify unique transmission categories:

vehicles_selected %>%
  distinct(trans) %>%
  arrange(trans)
# A tibble: 10 × 1
   trans     
   <chr>     
 1 auto(av)  
 2 auto(l3)  
 3 auto(l4)  
 4 auto(l5)  
 5 auto(l6)  
 6 auto(s4)  
 7 auto(s5)  
 8 auto(s6)  
 9 manual(m5)
10 manual(m6)

The transmission variable contains 10 unique categories, including eight automatic and two manual transmission categories. To simplify the analysis and make comparisons easier, these categories will be grouped into two main categories: Automatic and Manual.

Identify unique drivetrain categories:

vehicles_selected %>%
  distinct(drv) %>%
  arrange(drv)
# A tibble: 3 × 1
  drv  
  <chr>
1 4    
2 f    
3 r    

The drivetrain variable contains three unique categories:

4: Four-wheel drive
f: Front-wheel drive
r: Rear-wheel drive

These abbreviated values will be replaced with descriptive labels to improve readability and make the analysis and visualizations easier to interpret.

4.4.4 Transform Categorical Variables

I will use mutate(), case_when(), and str_detect() to transform the transmission and drivetrain variables. The transmission categories will be grouped into Automatic and Manual, while the drivetrain abbreviations will be replaced with descriptive labels.

vehicles_clean <- vehicles_selected %>%
  mutate(
    transmission_type = case_when(
      str_detect(trans, "^auto") ~ "Automatic",
      str_detect(trans, "^manual") ~ "Manual",
      TRUE ~ NA_character_
    ),
    drivetrain_type = case_when(
      drv == "4" ~ "Four-wheel drive",
      drv == "f" ~ "Front-wheel drive",
      drv == "r" ~ "Rear-wheel drive",
      TRUE ~ NA_character_
    )
  )

vehicles_clean %>%
  select(trans, transmission_type, drv, drivetrain_type) %>%
  distinct()
# A tibble: 24 × 4
   trans      transmission_type drv   drivetrain_type  
   <chr>      <chr>             <chr> <chr>            
 1 auto(l5)   Automatic         f     Front-wheel drive
 2 manual(m5) Manual            f     Front-wheel drive
 3 manual(m6) Manual            f     Front-wheel drive
 4 auto(av)   Automatic         f     Front-wheel drive
 5 manual(m5) Manual            4     Four-wheel drive 
 6 auto(l5)   Automatic         4     Four-wheel drive 
 7 manual(m6) Manual            4     Four-wheel drive 
 8 auto(s6)   Automatic         4     Four-wheel drive 
 9 auto(l4)   Automatic         r     Rear-wheel drive 
10 manual(m6) Manual            r     Rear-wheel drive 
# ℹ 14 more rows

The transformation successfully grouped the 10 original transmission categories into two main categories: Automatic and Manual. The drivetrain abbreviations were also converted into three descriptive categories: Four-wheel drive, Front-wheel drive, and Rear-wheel drive. The original variables were retained, and two new variables were created. These transformations improve data readability and make comparisons between vehicle categories easier.

4.4.5 Verify Transformed Categories

I will use count() to examine the distribution of vehicles across the newly created transmission and drivetrain categories.

Count vehicles by transmission type:

vehicles_clean %>%
  count(transmission_type) %>%
  kable(caption = "Vehicle Distribution by Transmission Type")
Vehicle Distribution by Transmission Type
transmission_type n
Automatic 157
Manual 77

The dataset contains 157 automatic (67.1%) and 77 manual (32.9%) vehicle configurations. Automatic transmission is more common in the dataset, representing approximately two-thirds of all observations. This difference in group sizes should be considered when comparing fuel efficiency between the two transmission types.

Count vehicles by drivetrain type:

vehicles_clean %>%
  count(drivetrain_type) %>%
  kable(caption = "Vehicle Distribution by Drivetrain Type")
Vehicle Distribution by Drivetrain Type
drivetrain_type n
Four-wheel drive 103
Front-wheel drive 106
Rear-wheel drive 25

Front-wheel drive is the most common drivetrain type, with 106 observations (45.3%), followed by four-wheel drive with 103 observations (44.0%). Rear-wheel drive is the least common category, with 25 observations (10.7%). Front-wheel drive and four-wheel drive have similar group sizes, while rear-wheel drive has considerably fewer observations. This difference should be considered when comparing fuel efficiency across drivetrain types.

4.5 Correlation Analysis

Research Question 1: What is the relationship between engine displacement and fuel efficiency?

I will examine the relationship between engine displacement and highway fuel efficiency. Engine displacement is measured in liters, while fuel efficiency is measured in miles per gallon (MPG). I will use summarise() and cor() to calculate the correlation coefficient between these two variables.

correlation_result <- vehicles_clean %>%
  summarise(
    Correlation = round(cor(displ, hwy), 3)
  )

kable(correlation_result,
      caption = "Correlation Between Engine Displacement and Highway MPG")
Correlation Between Engine Displacement and Highway MPG
Correlation
-0.766

The correlation coefficient between engine displacement and highway fuel efficiency is -0.766, indicating a strong negative relationship. As engine displacement increases, highway fuel efficiency generally decreases. In other words, vehicles with larger engines tend to achieve lower miles per gallon (MPG) than vehicles with smaller engines. However, correlation does not imply causation, and other vehicle characteristics may also influence fuel efficiency.

I will use geom_point() to create a scatter plot and geom_smooth() to add a linear regression trend line. This visualization will help identify the direction and pattern of the relationship between engine displacement and highway fuel efficiency.

ggplot(vehicles_clean, aes(x = displ, y = hwy)) +
  geom_point(color = "steelblue", alpha = 0.6, size = 2.5) +
  geom_smooth(method = "lm", formula = y ~ x,
              color = "darkred", se = TRUE) +
  labs(
    title = "Engine Displacement vs. Highway Fuel Efficiency",
    x = "Engine Displacement (Liters)",
    y = "Highway Fuel Efficiency (MPG)"
  ) +
  theme_minimal()

The downward-sloping regression line supports the correlation analysis. However, vehicles with similar engine sizes sometimes have different MPG values, suggesting that other vehicle characteristics may also influence fuel efficiency.

4.6 Summary Statistics by Number of Cylinders

Research Question 2: How does fuel efficiency vary by the number of cylinders?

I will use group_by() and summarise() to calculate the number of observations, mean, median, and standard deviation of highway fuel efficiency for each cylinder category. This analysis will help identify differences in fuel efficiency among vehicles with different numbers of cylinders.

cylinder_summary <- vehicles_clean %>%
  group_by(cyl) %>%
  summarise(
    Vehicle_Count = n(),
    Mean_MPG = round(mean(hwy), 2),
    Median_MPG = round(median(hwy), 2),
    SD_MPG = round(sd(hwy), 2)
  ) %>%
  arrange(cyl)

kable(cylinder_summary,
      caption = "Highway Fuel Efficiency by Number of Cylinders")
Highway Fuel Efficiency by Number of Cylinders
cyl Vehicle_Count Mean_MPG Median_MPG SD_MPG
4 81 28.80 29 4.52
5 4 28.75 29 0.50
6 79 22.82 24 3.69
8 70 17.63 17 3.26

Vehicles with four cylinders have the highest average highway fuel efficiency at 28.80 MPG, followed by five-cylinder vehicles at 28.75 MPG. Six-cylinder vehicles have an average of 22.82 MPG, while eight-cylinder vehicles have the lowest average at 17.63 MPG. These results indicate that vehicles with fewer cylinders generally have higher fuel efficiency. Four-cylinder vehicles have the highest variability, with a standard deviation of 4.52 MPG. However, the five-cylinder category contains only four observations. Therefore, the results for this category should be interpreted with caution.

I will use geom_boxplot() to compare the distribution of highway fuel efficiency across different cylinder categories. The boxplot will help identify differences in median values, variability, and potential outliers.

ggplot(vehicles_clean,
       aes(x = factor(cyl), y = hwy, fill = factor(cyl))) +
  geom_boxplot(alpha = 0.7) +
  labs(
    title = "Highway Fuel Efficiency by Number of Cylinders",
    x = "Number of Cylinders",
    y = "Highway Fuel Efficiency (MPG)"
  ) +
  theme_minimal() +
  theme(legend.position = "none")

The boxplot shows that median highway MPG generally decreases as the number of cylinders increases. Four-cylinder vehicles have several high outliers, while five-cylinder vehicles show very little variability.

4.7 Summary Statistics by Transmission Type

Research Question 3: How does fuel efficiency differ between automatic and manual transmission vehicles?

I will use group_by() and summarise() to calculate summary statistics for automatic and manual transmission vehicles. This analysis will help determine whether highway fuel efficiency differs between the two transmission types.

transmission_summary <- vehicles_clean %>%
  group_by(transmission_type) %>%
  summarise(
    Vehicle_Count = n(),
    Mean_MPG = round(mean(hwy), 2),
    Median_MPG = round(median(hwy), 2),
    SD_MPG = round(sd(hwy), 2)
  ) %>%
  arrange(desc(Mean_MPG))

kable(transmission_summary,
      caption = "Highway Fuel Efficiency by Transmission Type")
Highway Fuel Efficiency by Transmission Type
transmission_type Vehicle_Count Mean_MPG Median_MPG SD_MPG
Manual 77 25.78 26 5.96
Automatic 157 22.29 22 5.62

Manual transmission vehicles have an average highway fuel efficiency of 25.78 MPG, compared to 22.29 MPG for automatic transmission vehicles. The difference in average fuel efficiency is 3.49 MPG. Manual vehicles also have a higher median of 26 MPG, compared to 22 MPG for automatic vehicles. Both groups show similar variability, with standard deviations of 5.96 MPG and 5.62 MPG, respectively. Overall, manual transmission vehicles tend to have higher highway fuel efficiency in this dataset. However, differences in group sizes, engine displacement, number of cylinders, and vehicle class should also be considered when interpreting these results.

I will use geom_violin() to visualize the distribution and density of highway fuel efficiency for each transmission type. I will also add geom_boxplot() to display the median and interquartile range within each distribution.

ggplot(vehicles_clean,
       aes(x = transmission_type, y = hwy,
           fill = transmission_type)) +
  geom_violin(alpha = 0.6, trim = TRUE) +
  geom_boxplot(width = 0.15, fill = "white") +
  labs(
    title = "Highway Fuel Efficiency by Transmission Type",
    x = "Transmission Type",
    y = "Highway Fuel Efficiency (MPG)"
  ) +
  theme_minimal() +
  theme(legend.position = "none")

The violin plot shows that the fuel efficiency distribution of manual vehicles is mainly concentrated between 24 and 30 MPG. The overlapping distributions suggest that transmission type alone does not explain all differences in fuel efficiency.

4.8 Summary Statistics by Drivetrain Type

Research Question 4: How does fuel efficiency vary across different drivetrain types?

I will use group_by() and summarise() to calculate summary statistics for each drivetrain type. This analysis will help identify differences in highway fuel efficiency among front-wheel drive, rear-wheel drive, and four-wheel drive vehicles.

drivetrain_summary <- vehicles_clean %>%
  group_by(drivetrain_type) %>%
  summarise(
    Vehicle_Count = n(),
    Mean_MPG = round(mean(hwy), 2),
    Median_MPG = round(median(hwy), 2),
    SD_MPG = round(sd(hwy), 2)
  ) %>%
  arrange(desc(Mean_MPG))

kable(drivetrain_summary,
      caption = "Highway Fuel Efficiency by Drivetrain Type")
Highway Fuel Efficiency by Drivetrain Type
drivetrain_type Vehicle_Count Mean_MPG Median_MPG SD_MPG
Front-wheel drive 106 28.16 28 4.21
Rear-wheel drive 25 21.00 21 3.66
Four-wheel drive 103 19.17 18 4.08

Front-wheel drive vehicles have the highest average highway fuel efficiency at 28.16 MPG, followed by rear-wheel drive vehicles at 21.00 MPG. Four-wheel drive vehicles have the lowest average at 19.17 MPG. The difference in average fuel efficiency between front-wheel drive and four-wheel drive vehicles is 8.99 MPG. The median values also support these findings. However, rear-wheel drive vehicles have only 25 observations, which is considerably fewer than the other two categories. Overall, front-wheel drive vehicles tend to achieve higher highway fuel efficiency in this dataset. Other factors, such as vehicle weight, engine size, and vehicle class, may also contribute to these differences.

I will use fct_reorder() from the forcats package to reorder drivetrain categories based on their average highway fuel efficiency. I will use geom_col() to create a bar chart and geom_text() to display the average MPG values on each bar.

ggplot(drivetrain_summary,
       aes(x = fct_reorder(drivetrain_type, Mean_MPG),
           y = Mean_MPG,
           fill = drivetrain_type)) +
  geom_col(width = 0.65, alpha = 0.8) +
  geom_text(aes(label = Mean_MPG),
            hjust = -0.2, size = 4) +
  coord_flip() +
  scale_y_continuous(
    expand = expansion(mult = c(0, 0.15))
  ) +
  labs(
    title = "Average Highway Fuel Efficiency by Drivetrain Type",
    x = "Drivetrain Type",
    y = "Average Highway Fuel Efficiency (MPG)"
  ) +
  theme_minimal() +
  theme(legend.position = "none")

The bar chart visually highlights the difference in average highway fuel efficiency across drivetrain categories. The use of fct_reorder() and geom_text() makes the comparison clearer and easier to interpret.

5. Conclusion

In this extension, I expanded Patricio Romero’s original vignette by examining the relationship between additional vehicle characteristics and highway fuel efficiency using the same mpg dataset.

The main findings of this analysis are:

  • Engine Displacement: A strong negative correlation (-0.766) was found between engine displacement and highway fuel efficiency. Vehicles with larger engines generally achieve lower MPG.

  • Number of Cylinders: Four-cylinder vehicles have the highest average highway fuel efficiency (28.80 MPG), while eight-cylinder vehicles have the lowest (17.63 MPG).

  • Transmission Type: Manual transmission vehicles have higher average highway fuel efficiency (25.78 MPG) than automatic transmission vehicles (22.29 MPG).

  • Drivetrain Type: Front-wheel drive vehicles have the highest average highway fuel efficiency (28.16 MPG), while four-wheel drive vehicles have the lowest (19.17 MPG).

This extension introduces additional Tidyverse functions, including across(), case_when(), str_detect(), count(), fct_reorder(), geom_smooth(), geom_boxplot(), geom_violin(), and geom_text(). These functions demonstrate how additional data transformation and visualization techniques can provide new insights into an existing dataset.

Limitations:

The dataset contains only 234 vehicle configurations from the 1999 and 2008 model years. Therefore, the results may not represent modern vehicles. Unequal group sizes, particularly the small number of five-cylinder vehicles, may also limit the reliability of comparisons.

Other factors, such as vehicle weight, aerodynamics, and fuel type, may influence fuel efficiency. Additionally, this analysis focuses only on highway MPG and identifies associations rather than causal relationships.

Future studies could use a larger and more recent dataset, include city fuel efficiency, and apply multiple regression analysis to examine several vehicle characteristics simultaneously.

6. Citation

I used ChatGPT (GPT-6), developed by OpenAI, to help me understand some of the functions I used in this assignment and to check my work.

OpenAI. (2026). ChatGPT (GPT-6) [Large language model]. [https://chatgpt.com/ Accessed November 30, 2026].