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:
ggplot2.You do not need to download any data. Everything used here is already included in R.
Work through the steps in order. For each step:
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.
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:
Rcourse and create the project.analysis_mtcars.R.Type the following line in your script and run it with Ctrl+Enter:
#> [1] 2
Checkpoint: The Console should show [1]
2. R is working.
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:
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.
The symbol <- saves a value in an object. The
function c() combines values into a vector.
#> [1] 10
#> [1] 6
#> [1] 2.345208
#> [1] FALSE FALSE TRUE TRUE TRUE
#> [1] 8 8 7
NA means a missing value. Use na.rm = TRUE
to omit missing values from a particular calculation.
#> [1] NA
#> [1] 6.333333
#> [1] 1
Checkpoint: mean(v) returns
NA, while mean(v, na.rm = TRUE) returns
approximately 6.33. There is one missing value.
Load mtcars, which contains information about 32 cars.
In RStudio, you can type ?mtcars in the Console to open the
codebook.
#> [1] 32 11
#> [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
#> [11] "carb"
#> 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
#> '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 |
#> [1] 0
Checkpoint: dim(mtcars) gives 32
11: 32 rows and 11 columns. There are no missing values.
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.
#>
#> automatic manual
#> 0 19 0
#> 1 0 13
#>
#> 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.
These checks stop the script if an important condition is false.
Save the labelled data as a new CSV file. Do not overwrite your original data in your own projects.
Checkpoint: mtcars_labelled.csv appears
in your project folder. The stopifnot() command produces no
error.
Start with the number of cars in each cylinder group.
#>
#> 4cyl 6cyl 8cyl Sum
#> 11 7 14 32
#>
#> 4cyl 6cyl 8cyl
#> 0.344 0.219 0.438
For example, 14 of the 32 cars have eight cylinders: 43.8%.
Use summary() for a quick overview and
psych::describe() for more descriptive statistics.
#> Min. 1st Qu. Median Mean 3rd Qu. Max.
#> 10.40 15.43 19.20 20.09 22.80 33.90
#> 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
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.
Run each block and look at the Plots pane in RStudio.
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.
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.
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.
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.
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”.
Because there are two groups and a numeric outcome, use Welch’s t-test.
#>
#> 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.
Because there are three groups and a numeric outcome, use one-way ANOVA.
#> 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
#> 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.
Because both variables are categorical, create a frequency table and use a chi-square test.
#>
#> V straight Sum
#> automatic 12 7 19
#> manual 6 7 13
#> Sum 18 14 32
#>
#> Pearson's Chi-squared test with Yates' continuity correction
#>
#> data: tab_av
#> X-squared = 0.34754, df = 1, p-value = 0.5555
#> [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.
Fit the same straight line shown in the scatterplot.
#>
#> 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
#> 2.5 % 97.5 %
#> (Intercept) 33.450500 41.119753
#> wt -6.486308 -4.202635
Look for the row named wt in the coefficients table:
Use the wording “heavier cars are associated with lower mpg”, not “weight causes lower mpg”.
In ggplot2, aes() connects variables to the
plot, and geom_*() chooses the visual form. Layers are
joined with +.
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_cylp_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_weightCheckpoint: Open the figures folder.
You should see ggplot_cyl.png and
ggplot_mpg_weight.png.
You have now completed the main Lecture 6 lab workflow. Your script should contain:
ggplot2 figures saved as PNG files.Now test the complete script:
analysis_mtcars.R.Finished: If the script runs from beginning to end after restarting R, your analysis is reproducible.
Try one additional question using the skills above:
Does the
heavyindicator predict lower mpg after controlling for cylinder group?
Hint:
Write one sentence describing the direction of the heavy
coefficient. Do not use causal language.
| 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. |