Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

R Project: Do Manual Cars Really Get Better Mileage? (mtcars)

A complete R analysis from question to conclusion on the mtcars data: inspect, clean, summarize, visualize, test, model, and discover how weight confounds the transmission effect.

This project walks through a small but complete data analysis in R, the way you would do it at work: start with a question, look at the data, clean it, summarize it, draw pictures, test a claim, build a model, and write down an honest conclusion. We use mtcars, the classic data set built into R: 32 cars from a 1974 US magazine, with fuel economy and ten design measurements.

The question: Do cars with manual transmissions get better mileage than cars with automatic transmissions?

The answer turns out to be instructive, because the obvious answer ("yes, by 7 mpg") is not quite the right one. The project uses ideas from earlier lessons: descriptive statistics, hypothesis tests, regression and ggplot2.

R is not available on this site, so the R code is read-only and the charts are described. Every number quoted was reproduced with an independent Python calculation on the same data (the block at the end re-runs it). Paste the R code into RStudio, one step at a time, to follow along.

Step 1: Set up and inspect

R
library(dplyr)
library(ggplot2)

data(mtcars)
dim(mtcars)        # 32 11
names(mtcars)
# "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"
str(mtcars)
head(mtcars, 3)

Always look before you compute: dim() gives the shape (32 rows, 11 columns), str() the type of each column, head() the first rows. The help page ?mtcars explains the variables. The ones we need:

Column Meaning
mpg miles per US gallon (the outcome)
am transmission: 0 = automatic, 1 = manual
wt weight in 1,000 lb
hp gross horsepower
cyl number of cylinders

Check for problems: anyNA(mtcars) is FALSE (no missing values), and summary(mtcars$mpg) shows a range from 10.4 to 33.9 with nothing absurd. A few minutes of checking at the start saves hours later.

Step 2: Clean and label

am and cyl are coded as numbers but are really categories. Convert them to labeled factors so that tables and plots read well and models treat them correctly:

R
cars <- mtcars |>
  mutate(
    am  = factor(am, levels = c(0, 1), labels = c("automatic", "manual")),
    cyl = factor(cyl)
  )
table(cars$am)
# automatic    manual 
#        19        13 

(The first line of a one-way table() is a blank line holding the variable name, which we omit here.) We keep the original mtcars untouched and work on a copy, so that the cleaning steps are visible in the script and repeatable.

Step 3: Summarize by group

R
aggregate(mpg ~ am, data = cars, FUN = mean)
#          am      mpg
# 1 automatic 17.14737
# 2    manual 24.39231

cars |>
  group_by(am) |>
  summarise(n = n(), mean_mpg = mean(mpg), sd_mpg = sd(mpg), mean_wt = mean(wt))

Manual cars average 24.39 mpg and automatic cars 17.15 mpg: a difference of 7.24 mpg. That is the headline number. But check the other columns too: the mean_wt column shows that the automatic cars average 3.77 (thousand lb) and manual cars only 2.41. Remember that for later.

Step 4: Look at the data

Pictures often show what summaries hide.

R
ggplot(cars, aes(am, mpg)) +
  geom_boxplot() +
  geom_jitter(width = 0.1, height = 0)

ggplot(cars, aes(wt, mpg, color = am)) +
  geom_point(size = 3) +
  geom_smooth(method = "lm", se = FALSE)

The first chart shows the box for manual cars sitting clearly above the box for automatic cars, with all raw points drawn on top. The second plots mileage against weight, colored by transmission. Two features stand out: mileage falls steadily with weight for both types, and the manual (light) cars cluster at the left of the chart where weight is low. The two fitted lines nearly overlap: at the same weight, the two transmissions look similar. That is the clue that weight may explain the gap.

Also check the distribution of weight by transmission and a cross-table of cylinders:

R
table(cars$am, cars$cyl)
# rows automatic / manual, columns 4 / 6 / 8 cylinders:
#   automatic:  3  4 12
#   manual:     8  3  2

Automatic cars in this sample are mostly 8-cylinder; manuals are mostly 4-cylinder.

Step 5: Test the difference

Is a gap of 7.24 mpg larger than chance variation between two samples of this size?

R
t.test(mpg ~ am, data = cars)
# Welch t-test: t = -3.7671, df = 18.332, p-value = 0.001374
# 95 percent CI for the difference (automatic - manual): -11.28 to -3.21

The p-value of 0.0014 says that a difference this large would be rare if transmissions made no difference in this kind of sample. The confidence interval says the true gap in the sample population is somewhere between about 3.2 and 11.3 mpg. This is a statistical statement about the raw comparison. It does not say the transmission causes the gap, which is the next question.

Step 6: Model, and adjust for weight

A regression lets us compare cars of the same weight. First the unadjusted model, which reproduces the 7.24 gap, then the adjusted one:

R
m1 <- lm(mpg ~ am, data = cars)
coef(m1)
# (Intercept)    ammanual 
#    17.14737     7.24494 

m2 <- lm(mpg ~ wt + am, data = cars)
coef(m2)
# (Intercept)          wt    ammanual 
#  37.3215513  -5.3528114  -0.0236152 

In the first model the manual coefficient is the 7.24 difference in means. In the second, once weight is in the model, the transmission coefficient shrinks to -0.02 mpg with a standard error of about 1.55, which is practically zero (p = 0.99). Weight carries the effect: each extra 1,000 lb costs about 5.35 mpg whatever the transmission. R-squared is 0.753, almost the same as for weight alone (0.7528), so transmission adds essentially nothing.

R
summary(m2)$coefficients     # estimates, std. errors, t and p values
confint(m2)                  # wide interval for ammanual, including 0 comfortably

The correlation of weight with transmission is -0.69: manual cars in this data set are lighter, and lighter cars use less fuel. Weight is a confounder: a variable related to both the "treatment" (transmission) and the outcome (mileage). The raw comparison mixes up two things.

Step 7: Check the model

R
par(mfrow = c(2, 2)); plot(m2)

Look for a patternless residual plot and points near the line in the Q-Q plot. With only 32 cars, a few points (heavy luxury cars) have high influence; cooks.distance(m2) identifies them. A more careful analysis would also consider horsepower or the number of cylinders (see lm(mpg ~ wt + hp) in the regression lesson).

Step 8: Write the conclusion

A good conclusion states what was found, how sure we are, and what it does not show:

In the 1974 sample, manual cars averaged 7.2 mpg more than automatics (95% CI 3.2 to 11.3, Welch t-test, p = 0.001). However, manual cars in this sample were much lighter (2.4 vs 3.8 thousand lb). After adjusting for weight, the estimated transmission effect is about zero (-0.02 mpg, SE 1.55). The data are 32 cars from one year, so they cannot show that transmissions do not matter in general, only that weight explains the apparent advantage here.

That is the real skill in data analysis: not running t.test(), but noticing that the first answer is incomplete and saying exactly what the evidence supports.

Reproduce the numbers in Python

The Python block below recalculates every figure quoted above from the raw columns, so that you can verify the story yourself.

Python Python comparison: group means, Welch test and adjusted model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Make it your own

  1. Repeat the analysis with hp instead of wt. Does the transmission effect also vanish?
  2. Fit lm(mpg ~ wt * am), which lets the weight slope differ by transmission. Is the interaction significant?
  3. Make the plots publication-ready using ggplot2 customizing: title stating the finding, colorblind-safe palette, sorted labels.
  4. Wrap the cleaning and modelling steps in functions, and the whole thing in an R Markdown or Quarto document so that the report rebuilds with one click.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is it useful to convert am and cyl to factors?

    A numeric code would be treated as a quantity (a gradient in plots, a single slope in models). Factors make the categories explicit.
  2. 2. What does it mean that weight is a confounder here?

    Manual cars are lighter, and lighter cars use less fuel, so part of the apparent transmission effect is a weight effect.
  3. 3. In lm(mpg ~ wt + am), what does the coefficient for am measure?

    In a multiple regression each coefficient is the effect of that variable with the others held fixed.
  4. 4. Which conclusion is best supported by the analysis?

    A careful conclusion reports the adjusted result and states the limits of the data.

Summary

  • A good analysis follows a loop: question, inspect, clean, summarize, visualize, test, model, conclude.
  • The raw difference (7.2 mpg) was statistically significant, but weight confounds it.
  • Adjusting for weight in lm(mpg ~ wt + am) shrinks the transmission effect to about zero.
  • Say what the data show, how sure you are and what they cannot show.

Next: Project: Simulation and Resampling