1

library(dplyr)
library(tidyr)
library(ggplot2)

data(mpg)

1 a)

mpg_clean <- mpg %>%
  select(manufacturer, model, year, cyl, displ, cty, hwy, class, drv) %>%
  mutate(
    avg_mpg = round((cty + hwy) / 2, 1),
    efficiency_rating = case_when(
      avg_mpg < 20 ~ "Low",
      avg_mpg >= 20 & avg_mpg <= 25 ~ "Medium",
      avg_mpg > 25 ~ "High"
    ),
    engine_size = case_when(
      displ < 2.5 ~ "Small",
      displ >= 2.5 ~ "Large"
    )
  )

head(mpg_clean, 5)
## # A tibble: 5 × 12
##   manufacturer model  year   cyl displ   cty   hwy class   drv   avg_mpg
##   <chr>        <chr> <int> <int> <dbl> <int> <int> <chr>   <chr>   <dbl>
## 1 audi         a4     1999     4   1.8    18    29 compact f        23.5
## 2 audi         a4     1999     4   1.8    21    29 compact f        25  
## 3 audi         a4     2008     4   2      20    31 compact f        25.5
## 4 audi         a4     2008     4   2      21    30 compact f        25.5
## 5 audi         a4     1999     6   2.8    16    26 compact f        21  
## # ℹ 2 more variables: efficiency_rating <chr>, engine_size <chr>
dim(mpg_clean)
## [1] 234  12

1 b)

subset A

subset_A <- mpg_clean %>%
  filter(efficiency_rating == "High",
         engine_size == "Small")

subset_A
## # A tibble: 27 × 12
##    manufacturer model   year   cyl displ   cty   hwy class      drv   avg_mpg
##    <chr>        <chr>  <int> <int> <dbl> <int> <int> <chr>      <chr>   <dbl>
##  1 audi         a4      2008     4   2      20    31 compact    f        25.5
##  2 audi         a4      2008     4   2      21    30 compact    f        25.5
##  3 chevrolet    malibu  2008     4   2.4    22    30 midsize    f        26  
##  4 honda        civic   1999     4   1.6    28    33 subcompact f        30.5
##  5 honda        civic   1999     4   1.6    24    32 subcompact f        28  
##  6 honda        civic   1999     4   1.6    25    32 subcompact f        28.5
##  7 honda        civic   1999     4   1.6    23    29 subcompact f        26  
##  8 honda        civic   1999     4   1.6    24    32 subcompact f        28  
##  9 honda        civic   2008     4   1.8    26    34 subcompact f        30  
## 10 honda        civic   2008     4   1.8    25    36 subcompact f        30.5
## # ℹ 17 more rows
## # ℹ 2 more variables: efficiency_rating <chr>, engine_size <chr>
nrow(subset_A)
## [1] 27

subset B

subset_B <- mpg_clean %>%
  filter(class %in% c("compact",
                      "subcompact",
                      "midsize"))

subset_B
## # A tibble: 123 × 12
##    manufacturer model       year   cyl displ   cty   hwy class   drv   avg_mpg
##    <chr>        <chr>      <int> <int> <dbl> <int> <int> <chr>   <chr>   <dbl>
##  1 audi         a4          1999     4   1.8    18    29 compact f        23.5
##  2 audi         a4          1999     4   1.8    21    29 compact f        25  
##  3 audi         a4          2008     4   2      20    31 compact f        25.5
##  4 audi         a4          2008     4   2      21    30 compact f        25.5
##  5 audi         a4          1999     6   2.8    16    26 compact f        21  
##  6 audi         a4          1999     6   2.8    18    26 compact f        22  
##  7 audi         a4          2008     6   3.1    18    27 compact f        22.5
##  8 audi         a4 quattro  1999     4   1.8    18    26 compact 4        22  
##  9 audi         a4 quattro  1999     4   1.8    16    25 compact 4        20.5
## 10 audi         a4 quattro  2008     4   2      20    28 compact 4        24  
## # ℹ 113 more rows
## # ℹ 2 more variables: efficiency_rating <chr>, engine_size <chr>
nrow(subset_B)
## [1] 123

subset C

subset_C <- mpg_clean %>%
  filter(manufacturer %in% c("honda", "toyota"),
         year == 2008)

subset_C
## # A tibble: 18 × 12
##    manufacturer model           year   cyl displ   cty   hwy class drv   avg_mpg
##    <chr>        <chr>          <int> <int> <dbl> <int> <int> <chr> <chr>   <dbl>
##  1 honda        civic           2008     4   1.8    26    34 subc… f        30  
##  2 honda        civic           2008     4   1.8    25    36 subc… f        30.5
##  3 honda        civic           2008     4   1.8    24    36 subc… f        30  
##  4 honda        civic           2008     4   2      21    29 subc… f        25  
##  5 toyota       4runner 4wd     2008     6   4      16    20 suv   4        18  
##  6 toyota       4runner 4wd     2008     8   4.7    14    17 suv   4        15.5
##  7 toyota       camry           2008     4   2.4    21    31 mids… f        26  
##  8 toyota       camry           2008     4   2.4    21    31 mids… f        26  
##  9 toyota       camry           2008     6   3.5    19    28 mids… f        23.5
## 10 toyota       camry solara    2008     4   2.4    21    31 comp… f        26  
## 11 toyota       camry solara    2008     4   2.4    22    31 comp… f        26.5
## 12 toyota       camry solara    2008     6   3.3    18    27 comp… f        22.5
## 13 toyota       corolla         2008     4   1.8    28    37 comp… f        32.5
## 14 toyota       corolla         2008     4   1.8    26    35 comp… f        30.5
## 15 toyota       land cruiser …  2008     8   5.7    13    18 suv   4        15.5
## 16 toyota       toyota tacoma…  2008     4   2.7    17    22 pick… 4        19.5
## 17 toyota       toyota tacoma…  2008     6   4      15    18 pick… 4        16.5
## 18 toyota       toyota tacoma…  2008     6   4      16    20 pick… 4        18  
## # ℹ 2 more variables: efficiency_rating <chr>, engine_size <chr>
nrow(subset_C)
## [1] 18

subset D

subset_D <- mpg_clean %>%
  filter(cyl >= 6,
         avg_mpg < 20)

subset_D
## # A tibble: 101 × 12
##    manufacturer model           year   cyl displ   cty   hwy class drv   avg_mpg
##    <chr>        <chr>          <int> <int> <dbl> <int> <int> <chr> <chr>   <dbl>
##  1 audi         a6 quattro      1999     6   2.8    15    24 mids… 4        19.5
##  2 audi         a6 quattro      2008     8   4.2    16    23 mids… 4        19.5
##  3 chevrolet    c1500 suburba…  2008     8   5.3    14    20 suv   r        17  
##  4 chevrolet    c1500 suburba…  2008     8   5.3    11    15 suv   r        13  
##  5 chevrolet    c1500 suburba…  2008     8   5.3    14    20 suv   r        17  
##  6 chevrolet    c1500 suburba…  1999     8   5.7    13    17 suv   r        15  
##  7 chevrolet    c1500 suburba…  2008     8   6      12    17 suv   r        14.5
##  8 chevrolet    corvette        1999     8   5.7    15    23 2sea… r        19  
##  9 chevrolet    corvette        2008     8   7      15    24 2sea… r        19.5
## 10 chevrolet    k1500 tahoe 4…  2008     8   5.3    14    19 suv   4        16.5
## # ℹ 91 more rows
## # ℹ 2 more variables: efficiency_rating <chr>, engine_size <chr>
nrow(subset_D)
## [1] 101

Subset A mainly contains smaller engines with high fuel efficiency, while Subset D contains larger engines with at least six cylinders and poor fuel economy. Overall, larger engines and higher cylinder counts tends to reduce fuel efficiency, whereas smaller engines generally achieve better fuel economy.

1 c)

i)

manufacturer_summary <- mpg_clean %>%
  group_by(manufacturer) %>%
  summarise(
    mean_mpg = round(mean(avg_mpg), 2),
    mean_displ = round(mean(displ), 2),
    num_models = n()
  ) %>%
  arrange(desc(mean_mpg)) %>%
  slice_head(n = 5)

manufacturer_summary
## # A tibble: 5 × 4
##   manufacturer mean_mpg mean_displ num_models
##   <chr>           <dbl>      <dbl>      <int>
## 1 honda            28.5       1.71          9
## 2 volkswagen       25.1       2.26         27
## 3 hyundai          22.8       2.43         14
## 4 subaru           22.4       2.46         14
## 5 audi             22.0       2.54         18

ii)

class_year_summary <- mpg_clean %>%
  group_by(class, year) %>%
  summarise(
    median_hwy = median(hwy),
    median_cty = median(cty),
    .groups = "drop"
  ) %>%
  arrange(class, year)

class_year_summary
## # A tibble: 14 × 4
##    class       year median_hwy median_cty
##    <chr>      <int>      <dbl>      <dbl>
##  1 2seater     1999       24.5       15.5
##  2 2seater     2008       25         15  
##  3 compact     1999       26         19  
##  4 compact     2008       29         20.5
##  5 midsize     1999       26         18  
##  6 midsize     2008       28         19  
##  7 minivan     1999       22         16  
##  8 minivan     2008       23         16  
##  9 pickup      1999       17         13  
## 10 pickup      2008       17         13  
## 11 subcompact  1999       26         19  
## 12 subcompact  2008       26.5       18.5
## 13 suv         1999       17         14  
## 14 suv         2008       18         13

iii)

drive_summary <- mpg_clean %>%
  group_by(drv) %>%
  summarise(
    mean_hwy = round(mean(hwy), 2),
    sd_hwy = round(sd(hwy), 2),
    min_cty = min(cty),
    max_cty = max(cty)
  )

drive_summary
## # A tibble: 3 × 5
##   drv   mean_hwy sd_hwy min_cty max_cty
##   <chr>    <dbl>  <dbl>   <int>   <int>
## 1 4         19.2   4.08       9      21
## 2 f         28.2   4.21      11      35
## 3 r         21     3.66      11      18

Front-wheel drive (f) has the highest average highway mileage (28.16 mpg) while also having the highest standard deviation (4.21 mpg), meaning highway fuel economy varies the most among front-wheel drive vehicles. For buyers, this indicates that front-wheel drive is generally the most fuel-efficient option for highway driving, but fuel economy can differ considerably between individual models.

2

2 a)

ggplot(mpg,
       aes(x = displ,
           y = hwy,
           colour = class,
           size = cyl)) +
  geom_point(shape = 16,
             alpha = 0.6) +
  labs(
    title = "Engine Displacement vs Highway Mileage",
    x = "Engine Displacement (Litres)",
    y = "Highway Mileage (MPG)",
    colour = "Vehicle Class",
    size = "Cylinders"
  ) +
  theme_minimal()

The scatter plot shows a negative relationship between engine displacement and highway mileage. As engine displacement increases, highway fuel economy generally decreases. SUVs and pickup trucks tend to have the largest engines and the lowest highway mileage because they are heavier vehicles that require more fuel.


2 b)

ggplot(mpg,
       aes(x = drv,
           y = cty,
           fill = drv)) +
  geom_boxplot() +
  facet_wrap(~year) +
  scale_fill_manual(values = c(
    "4" = "steelblue",
    "f" = "forestgreen",
    "r" = "tomato"
  )) +
  labs(
    title = "City Mileage by Drive Train and Year",
    x = "Drive Train",
    y = "City Mileage (MPG)",
    fill = "Drive Train"
  ) +
  theme_bw()

The median city mileage for each drivetrain is similar between 1999 and 2008, although front-wheel drive vehicles generally achieve the highest city mileage. Overall, fuel economy appears to remain stable across the two years, with only small improvements for some drivetrain types.


2 c)

mpg %>%
  filter(year == 2008) %>%
  count(manufacturer) %>%
  ggplot(aes(
    x = reorder(manufacturer, n),
    y = n,
    fill = manufacturer
  )) +
  geom_col() +
  geom_text(aes(label = n),
            hjust = -0.1) +
  coord_flip() +
  labs(
    title = "Number of 2008 Vehicles by Manufacturer",
    x = "Manufacturer",
    y = "Number of Vehicles"
  ) +
  theme_bw() +
  guides(fill = "none")

The manufacturer with the longest horizontal bar has the greatest number of vehicle records in the 2008 dataset. Lincoln is the only one with a single record


2 d)

ggplot(mpg,
       aes(x = cty,
           y = hwy)) +
  geom_point(
    colour = "steelblue",
    alpha = 0.6
  ) +
  geom_smooth(
    method = "lm",
    colour = "red",
    fill = "pink"
  ) +
  geom_abline(
    slope = 1,
    intercept = 0,
    linetype = "dashed",
    colour = "grey50"
  ) +
  annotate(
    "text",
    x = 13,
    y = 13,
    label = "hwy = cty",
    colour = "black"
  ) +
  labs(
    title = "City Mileage vs Highway Mileage",
    x = "City Mileage (MPG)",
    y = "Highway Mileage (MPG)"
  ) +
  theme_classic()

Most data points lie above the dashed reference line, meaning that highway mileage is generally higher than city mileage for the same vehicle. Since vehicles consume less fuel during steady highway driving compared o stop and go city driving, this outcome was expected. The regression line fits the data well because the points follow a strong positive linear trend with relatively little scatter around the fitted line.