First, we load the required packages (Stat2Data,
dplyr, ggplot2) and load the
Sparrows dataset. We then construct two scatterplots to
explore the overall relationship between weight and wing length across
treatment groups.
# Load packages
library(Stat2Data)
library(dplyr)
library(ggplot2)
# Load dataset
data("Sparrows")
# Plain scatterplot
ggplot(Sparrows, aes(x = Weight, y = WingLength)) +
geom_point() +
labs(
title = "Sparrow Wing Length vs. Weight",
x = "Weight (grams)",
y = "Wing Length (mm)"
)
# Scatterplot colored and shaped by group (Treatment)
ggplot(Sparrows, aes(x = Weight, y = WingLength, color = Treatment, shape = Treatment)) +
geom_point() +
labs(
title = "Sparrow Wing Length vs. Weight by Treatment",
x = "Weight (grams)",
y = "Wing Length (mm)"
)
Observation: There are some outliers, but the groups seem to clump up at about 15g and 30 mm.
Next, we filter the dataset to isolate the control
group, construct a scatterplot with transparent points, and compute the
correlation coefficient (\(r\)).
# Filter data for the control group
my_group <- Sparrows %>%
filter(Treatment == "control")
# Scatterplot of my_group
ggplot(my_group, aes(x = Weight, y = WingLength)) +
geom_point(alpha = 0.6) +
labs(
title = "Control Sparrows: Wing Length vs. Weight",
x = "Weight (grams)",
y = "Wing Length (mm)"
)
# Calculate correlation coefficient r
cor(my_group$Weight, my_group$WingLength, use = "complete.obs")
## [1] 0.8059326
Analysis of Association: The relationship between weight and wing length for control sparrows is positive, linear, and strong, with a correlation coefficient of \(r = 0.81\).
We fit a simple linear regression model using WingLength
as the response variable and Weight as the explanatory
variable.
# Fit the linear model
model <- lm(WingLength ~ Weight, data = my_group)
# View the coefficients
coef(model)
## (Intercept) Weight
## 8.669793 1.309223
Model Results: - Intercept: 8.66 - Slope: 1.30
Slope Interpretation: For every 1 gram increase in a sparrow’s weight, the wing length is predicted to increase by 1.30 mm.
Finally, we overlay our fitted regression line onto the scatterplot using our calculated slope and intercept.
# Scatterplot with regression line overlay
ggplot(my_group, aes(x = Weight, y = WingLength)) +
geom_point(alpha = 0.6) +
geom_abline(intercept = 8.66, slope = 1.30, color = "steelblue", linewidth = 1) +
labs(
title = "Control Sparrows: Linear Regression Model",
subtitle = "WingLength = 8.66 + 1.30 * Weight (r = 0.81)",
x = "Weight (grams)",
y = "Wing Length (mm)"
)
Visual Verification: The regression line runs directly through the middle of the scatterplot data points as expected.