Before You Start

This is the core hands-on lab for Lecture 6. It follows the main worked example in the lecture slides: analyse R’s built-in mtcars data, from loading the data to producing statistical results and figures.

By the end of this lab, you will be able to:

  1. open and inspect a dataset in R;
  2. add labels to categorical variables;
  3. calculate descriptive statistics;
  4. draw basic plots;
  5. run a t-test, ANOVA, a chi-square test, correlation, and simple regression;
  6. save two figures with ggplot2.

You do not need to download any data. Everything used here is already included in R.

How to Use This Guide

Work through the steps in order. For each step:

  1. read the short instruction;
  2. copy the code into your R script;
  3. select the code and press Ctrl+Enter (Cmd+Enter on Mac);
  4. compare your result with the checkpoint.

Important: Type or copy code into an R script, not only into the Console. Your script is your lab notebook. Save it as analysis_mtcars.R.

Step 1: Open RStudio and Create a Project

If R and RStudio are not installed yet, download R first from CRAN, and then download RStudio Desktop. These are the installation sources given in slides 5–6 of Lecture 6. Accept the default installation settings.

Now create a project:

  1. In RStudio, click File → New Project.
  2. Choose New Directory → New Project.
  3. Name the folder Rcourse and create the project.
  4. Click File → New File → R Script.
  5. Save the script as analysis_mtcars.R.

Type the following line in your script and run it with Ctrl+Enter:

1 + 1
#> [1] 2

Checkpoint: The Console should show [1] 2. R is working.

Step 2: Prepare the Packages

Lecture 6 uses psych for descriptive statistics, dplyr for a grouped table, and ggplot2 for figures.

If this is your first time using these packages, copy the next line into the Console and press Enter. You need to do this only once on each computer:

install.packages(c("psych", "dplyr", "ggplot2"))

After installation, put these lines in your script and run them. You load packages every time you start a new R session.

library(psych)
library(dplyr)
library(ggplot2)

# This folder will hold the figures created later.
dir.create("figures", showWarnings = FALSE)

Checkpoint: There should be no line beginning with Error. A folder named figures now exists in your project.

Step 3: Try a Few Basic R Commands

The symbol <- saves a value in an object. The function c() combines values into a vector.

x <- 5
x * 2
#> [1] 10
score <- c(4, 3, 8, 8, 7)
mean(score)
#> [1] 6
sd(score)
#> [1] 2.345208
score > 5
#> [1] FALSE FALSE  TRUE  TRUE  TRUE
score[score > 5]
#> [1] 8 8 7

NA means a missing value. Use na.rm = TRUE to omit missing values from a particular calculation.

v <- c(4, 8, NA, 7)
mean(v)
#> [1] NA
mean(v, na.rm = TRUE)
#> [1] 6.333333
sum(is.na(v))
#> [1] 1

Checkpoint: mean(v) returns NA, while mean(v, na.rm = TRUE) returns approximately 6.33. There is one missing value.

Step 4: Load and Inspect the Data

Load mtcars, which contains information about 32 cars. In RStudio, you can type ?mtcars in the Console to open the codebook.

data(mtcars)

dim(mtcars)
#> [1] 32 11
names(mtcars)
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
#> [11] "carb"
head(mtcars, 3)
#>                mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
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 ...

The most important variables for this lab are:

Variable Meaning
mpg Fuel economy: miles per US gallon
wt Weight in 1,000 pounds
hp Gross horsepower
am Transmission: 0 = automatic, 1 = manual
cyl Number of cylinders: 4, 6, or 8
vs Engine layout: 0 = V-shaped, 1 = straight
sum(is.na(mtcars))
#> [1] 0

Checkpoint: dim(mtcars) gives 32 11: 32 rows and 11 columns. There are no missing values.

Step 5: Add Clear Category Labels

Numbers such as 0 and 1 are codes, not meaningful labels. Create new factor variables using the codebook. The original columns remain unchanged.

Car names are stored as row names, so first copy them into a regular column called model.

mtcars$model <- rownames(mtcars)

mtcars$am_f <- factor(
  mtcars$am,
  levels = c(0, 1),
  labels = c("automatic", "manual")
)

mtcars$cyl_f <- factor(
  mtcars$cyl,
  levels = c(4, 6, 8),
  labels = c("4cyl", "6cyl", "8cyl")
)

mtcars$gear_f <- factor(
  mtcars$gear,
  levels = c(3, 4, 5),
  labels = c("3gears", "4gears", "5gears")
)

mtcars$vs_f <- factor(
  mtcars$vs,
  levels = c(0, 1),
  labels = c("V", "straight")
)

Always check that the old codes and new labels match.

table(mtcars$am, mtcars$am_f)
#>    
#>     automatic manual
#>   0        19      0
#>   1         0     13
table(mtcars$cyl_f)
#> 
#> 4cyl 6cyl 8cyl 
#>   11    7   14

Create the two simple indicator variables introduced in Lecture 6.

mtcars$heavy <- ifelse(mtcars$wt >= 3.5, 1, 0)
mtcars$efficient <- ifelse(mtcars$mpg >= 25, 1, 0)

table(mtcars$heavy)
#> 
#>  0  1 
#> 21 11

Checkpoint: There are 19 automatic and 13 manual cars. The cylinder groups contain 11, 7, and 14 cars. The heavy indicator identifies 11 cars weighing at least 3,500 pounds.

Step 6: Check and Save the Cleaned Data

These checks stop the script if an important condition is false.

stopifnot(
  nrow(mtcars) == 32,
  all(mtcars$cyl %in% c(4, 6, 8)),
  all(mtcars$am %in% c(0, 1))
)

Save the labelled data as a new CSV file. Do not overwrite your original data in your own projects.

write.csv(
  mtcars,
  "mtcars_labelled.csv",
  fileEncoding = "UTF-8",
  row.names = FALSE
)

Checkpoint: mtcars_labelled.csv appears in your project folder. The stopifnot() command produces no error.

Step 7: Describe the Data

Counts and percentages

Start with the number of cars in each cylinder group.

tab <- table(mtcars$cyl_f)
addmargins(tab)
#> 
#> 4cyl 6cyl 8cyl  Sum 
#>   11    7   14   32
round(prop.table(tab), 3)
#> 
#>  4cyl  6cyl  8cyl 
#> 0.344 0.219 0.438

For example, 14 of the 32 cars have eight cylinders: 43.8%.

Numeric variables

Use summary() for a quick overview and psych::describe() for more descriptive statistics.

summary(mtcars$mpg)
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>   10.40   15.43   19.20   20.09   22.80   33.90
psych::describe(mtcars[, c("mpg", "wt", "hp")])
#>     vars  n   mean    sd median trimmed   mad   min    max  range skew kurtosis
#> mpg    1 32  20.09  6.03  19.20   19.70  5.41 10.40  33.90  23.50 0.61    -0.37
#> wt     2 32   3.22  0.98   3.33    3.15  0.77  1.51   5.42   3.91 0.42    -0.02
#> hp     3 32 146.69 68.56 123.00  141.19 77.10 52.00 335.00 283.00 0.73    -0.14
#>        se
#> mpg  1.07
#> wt   0.17
#> hp  12.12

A grouped summary table

Read the pipe |> as “and then”: take mtcars, group it by transmission, and calculate the requested statistics.

by_am <- mtcars |>
  group_by(am_f) |>
  summarise(
    n = n(),
    mean_mpg = mean(mpg),
    sd_mpg = sd(mpg)
  )

by_am
#> # A tibble: 2 × 4
#>   am_f          n mean_mpg sd_mpg
#>   <fct>     <int>    <dbl>  <dbl>
#> 1 automatic    19     17.1   3.83
#> 2 manual       13     24.4   6.17

Checkpoint: Manual cars average approximately 24.39 mpg; automatic cars average approximately 17.15 mpg. This is a descriptive difference, not yet a statistical test.

Step 8: Draw Basic Plots

Run each block and look at the Plots pane in RStudio.

A bar chart for a categorical variable

barplot(
  sort(table(mtcars$cyl_f), decreasing = TRUE),
  col = "#5B8DBE",
  las = 1,
  ylim = c(0, 15),
  ylab = "Number of cars (n = 32)",
  main = "Engine layout in the 32 cars"
)

The eight-cylinder group is the largest. A bar chart starts at zero.

A histogram for a numeric variable

hist(
  mtcars$mpg,
  breaks = 10,
  col = "#5B8DBE",
  border = "white",
  main = "Fuel economy of 32 cars (1973-74)",
  xlab = "Miles per US gallon"
)
rug(mtcars$mpg)
abline(v = mean(mtcars$mpg), col = "#A6322B", lwd = 2)
abline(v = median(mtcars$mpg), col = "#C08A1E", lwd = 2, lty = 2)

The solid line is the mean and the dashed line is the median. Look at the shape, centre, spread, and possible unusual observations.

A boxplot for group comparison

boxplot(
  mpg ~ cyl_f,
  data = mtcars,
  col = "#5B8DBE",
  las = 1,
  xlab = "Number of cylinders",
  ylab = "Miles per US gallon"
)

The thick line is the median. The box contains the middle 50% of observations. Points outside the whiskers should be examined, not automatically deleted.

A scatterplot for two numeric variables

plot(
  mpg ~ wt,
  data = mtcars,
  pch = 19,
  col = adjustcolor("#142A55", .55),
  xlab = "Weight (1000 lbs)",
  ylab = "Miles per US gallon"
)
abline(lm(mpg ~ wt, data = mtcars), col = "#A6322B", lwd = 2)

The downward pattern means that heavier cars generally have lower fuel economy. This is an association, not proof of causation.

Step 9: Run the Basic Statistical Tests

For each test, first identify the question, then read the estimate, confidence interval, and p value. Remember: p >= .05 means insufficient evidence, not proof of “no effect”.

A. Do automatic and manual cars have different mean mpg?

Because there are two groups and a numeric outcome, use Welch’s t-test.

t_result <- t.test(mpg ~ am_f, data = mtcars)
t_result
#> 
#>  Welch Two Sample t-test
#> 
#> data:  mpg by am_f
#> t = -3.7671, df = 18.332, p-value = 0.001374
#> alternative hypothesis: true difference in means between group automatic and group manual is not equal to 0
#> 95 percent confidence interval:
#>  -11.280194  -3.209684
#> sample estimates:
#> mean in group automatic    mean in group manual 
#>                17.14737                24.39231

How to read it: Compare the two group means. The confidence interval is for automatic minus manual. Here, manual cars have higher average mpg, the p value is approximately .001, and the 95% confidence interval does not include zero.

B. Does mean mpg differ across the three cylinder groups?

Because there are three groups and a numeric outcome, use one-way ANOVA.

fit <- aov(mpg ~ cyl_f, data = mtcars)
summary(fit)
#>             Df Sum Sq Mean Sq F value   Pr(>F)    
#> cyl_f        2  824.8   412.4    39.7 4.98e-09 ***
#> Residuals   29  301.3    10.4                     
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
TukeyHSD(fit)
#>   Tukey multiple comparisons of means
#>     95% family-wise confidence level
#> 
#> Fit: aov(formula = mpg ~ cyl_f, data = mtcars)
#> 
#> $cyl_f
#>                 diff        lwr        upr     p adj
#> 6cyl-4cyl  -6.920779 -10.769350 -3.0722086 0.0003424
#> 8cyl-4cyl -11.563636 -14.770779 -8.3564942 0.0000000
#> 8cyl-6cyl  -4.642857  -8.327583 -0.9581313 0.0112287

How to read it: The overall ANOVA tests whether any group means differ. TukeyHSD() then compares the pairs. Read the adjusted p values in p adj. In this example, all three pairwise comparisons are statistically significant.

C. Are transmission and engine layout associated?

Because both variables are categorical, create a frequency table and use a chi-square test.

tab_av <- table(mtcars$am_f, mtcars$vs_f)
addmargins(tab_av)
#>            
#>              V straight Sum
#>   automatic 12        7  19
#>   manual     6        7  13
#>   Sum       18       14  32
chi_result <- chisq.test(tab_av)
chi_result
#> 
#>  Pearson's Chi-squared test with Yates' continuity correction
#> 
#> data:  tab_av
#> X-squared = 0.34754, df = 1, p-value = 0.5555
min(chi_result$expected)
#> [1] 5.6875

How to read it: The p value is approximately .56, so this small dataset does not provide sufficient evidence of an association. Chi-square tests use counts, not percentages. If expected counts are very small, Lecture 6 recommends considering Fisher’s exact test.

D. Are weight and fuel economy correlated?

Use Pearson correlation for these two numeric variables.

cor_result <- cor.test(mtcars$wt, mtcars$mpg)
cor_result
#> 
#>  Pearson's product-moment correlation
#> 
#> data:  mtcars$wt and mtcars$mpg
#> t = -9.559, df = 30, p-value = 1.294e-10
#> alternative hypothesis: true correlation is not equal to 0
#> 95 percent confidence interval:
#>  -0.9338264 -0.7440872
#> sample estimates:
#>        cor 
#> -0.8676594

How to read it: The correlation is approximately −0.87, indicating a strong negative linear relationship.

E. Can weight predict fuel economy?

Fit the same straight line shown in the scatterplot.

m0 <- lm(mpg ~ wt, data = mtcars)
summary(m0)
#> 
#> Call:
#> lm(formula = mpg ~ wt, data = mtcars)
#> 
#> Residuals:
#>     Min      1Q  Median      3Q     Max 
#> -4.5432 -2.3647 -0.1252  1.4096  6.8727 
#> 
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)  37.2851     1.8776  19.858  < 2e-16 ***
#> wt           -5.3445     0.5591  -9.559 1.29e-10 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 3.046 on 30 degrees of freedom
#> Multiple R-squared:  0.7528, Adjusted R-squared:  0.7446 
#> F-statistic: 91.38 on 1 and 30 DF,  p-value: 1.294e-10
confint(m0)
#>                 2.5 %    97.5 %
#> (Intercept) 33.450500 41.119753
#> wt          -6.486308 -4.202635

Look for the row named wt in the coefficients table:

  • Estimate: about −5.34. An additional 1,000 pounds predicts about 5.34 fewer mpg.
  • 95% confidence interval: it does not include zero.
  • R-squared: about .75, meaning that weight explains approximately 75% of the sample variation in mpg.

Use the wording “heavier cars are associated with lower mpg”, not “weight causes lower mpg”.

Step 10: Make and Save Two ggplot2 Figures

In ggplot2, aes() connects variables to the plot, and geom_*() chooses the visual form. Layers are joined with +.

Figure 1: Number of cars by cylinder group

cdat <- as.data.frame(table(mtcars$cyl_f))
names(cdat) <- c("engine", "cars")

p_cyl <- ggplot(
  cdat,
  aes(x = reorder(engine, -cars), y = cars)
) +
  geom_col(fill = "#142A55") +
  geom_text(aes(label = cars), vjust = -0.4, size = 4) +
  labs(
    title = "Engine sizes among the 32 cars",
    x = NULL,
    y = "Number of cars"
  ) +
  theme_minimal()

p_cyl

ggsave(
  "figures/ggplot_cyl.png",
  plot = p_cyl,
  width = 9,
  height = 5,
  dpi = 300
)

Figure 2: Weight and fuel economy by transmission

p_weight <- ggplot(mtcars, aes(wt, mpg)) +
  geom_jitter(
    width = .08,
    height = .08,
    alpha = .55,
    color = "#142A55"
  ) +
  geom_smooth(method = "lm", color = "#A6322B") +
  facet_wrap(~ am_f) +
  labs(
    x = "Weight (1000 lbs)",
    y = "Miles per US gallon"
  ) +
  theme_minimal()

p_weight

ggsave(
  "figures/ggplot_mpg_weight.png",
  plot = p_weight,
  width = 9,
  height = 5,
  dpi = 300
)

Checkpoint: Open the figures folder. You should see ggplot_cyl.png and ggplot_mpg_weight.png.

Step 11: Check That Your Work Is Reproducible

You have now completed the main Lecture 6 lab workflow. Your script should contain:

  • data loading and inspection;
  • factor labels and new variables;
  • data checks and a cleaned CSV file;
  • descriptive statistics and four basic plots;
  • t-test, ANOVA, chi-square, correlation, and simple regression;
  • two ggplot2 figures saved as PNG files.

Now test the complete script:

  1. Save analysis_mtcars.R.
  2. Click Session → Restart R.
  3. Run the whole script from top to bottom.
  4. Confirm that there is no error and that the CSV and PNG files are rebuilt.

Finished: If the script runs from beginning to end after restarting R, your analysis is reproducible.

Optional Practice from Lecture 6

Try one additional question using the skills above:

Does the heavy indicator predict lower mpg after controlling for cylinder group?

Hint:

# m_practice <- lm(mpg ~ heavy + cyl_f, data = mtcars)
# summary(m_practice)

Write one sentence describing the direction of the heavy coefficient. Do not use causal language.

Quick Troubleshooting

Problem What to do
there is no package called ... Run install.packages("package_name") once, then run library() again.
object 'am_f' not found Go back to Step 5 and run the factor-creation code.
object 'mtcars' not found Run data(mtcars) again.
A pipe or grouped summary does not work Run library(dplyr).
A ggplot command does not work Run library(ggplot2).
ggsave() cannot find the folder Run dir.create("figures", showWarnings = FALSE).
The script works only after you run extra Console commands Copy those commands into the script, restart R, and run everything again.