Scatterplots are the most common and effective tools for visualizing the relationship between two numeric variables.
The ncbirths dataset is a random sample of 1,000 cases taken from a larger dataset collected in 2004. Each case describes the birth of a single child born in North Carolina, along with various characteristics of the child (e.g. birth weight, length of gestation, etc.), the child’s mother (e.g. age, weight gained during pregnancy, smoking habits, etc.) and the child’s father (e.g. age). You can view the help file for these data by running ?ncbirths in the console.
library(openintro)
library(ggplot2)
library(dplyr)
head(ncbirths)
# Scatterplot of weight vs. weeks
ggplot(ncbirths, aes(x = weeks, y = weight)) +
geom_point()
If it is helpful, you can think of boxplots as scatterplots for which the variable on the x-axis has been discretized.
The cut() function takes two arguments: the continuous variable you want to discretize and the number of breaks that you want to make in that continuous variable in order to discretize it.
# Boxplot of weight vs. weeks
ggplot(data = ncbirths,
aes(x = cut(weeks, breaks = 5), y = weight)) +
geom_boxplot()
Note how the relationship no longer seems linear.
Creating scatterplots is simple and they are so useful that it is worthwhile to expose yourself to many examples. Over time, you will gain familiarity with the types of patterns that you see. You will begin to recognize how scatterplots can reveal the nature of the relationship between two variables.
We will be using several datasets listed below, available through the openintro package:
head(mammals)
# Mammals scatterplot
ggplot(mammals, aes(x = BodyWt, y = BrainWt)) +
geom_point()
head(mlbBat10)
ggplot(mlbBat10, aes(x = OBP, y = SLG)) +
geom_point()
head(bdims)
# Body dimensions scatterplot
ggplot(bdims, aes(x = hgt, y = wgt, color = as.factor(sex))) +
geom_point()
head(smoking)
# Smoking scatterplot
ggplot(smoking, aes(x = age, y = amtWeekdays)) +
geom_point()
The relationship between two variables may not be linear. In these cases we can sometimes see strange and even inscrutable patterns in a scatterplot of the data. Sometimes there really is no meaningful relationship between the two variables. Other times, a careful transformation of one or both of the variables can reveal a clear relationship.
Recall the bizarre pattern that we saw in the scatterplot between brain weight and body weight among mammals in a previous exercise. Can we use transformations to clarify this relationship?
ggplot2 provides several different mechanisms for viewing transformed relationships. The coord_trans() function transforms the coordinates of the plot. Alternatively, the scale_x_log10() and scale_y_log10() functions perform a base-10 log transformation of each axis. Note the differences in the appearance of the axes.
# Scatterplot with coord_trans()
ggplot(data = mammals, aes(x = BodyWt, y = BrainWt)) +
geom_point() +
coord_trans(x = "log10", y = "log10")
# Scatterplot with scale_x_log10() and scale_y_log10()
ggplot(data = mammals, aes(x = BodyWt, y = BrainWt)) +
geom_point() +
scale_x_log10() +
scale_y_log10()
we will discuss how outliers can affect the results of a linear regression model and how we can deal with them. For now, it is enough to simply identify them and note how the relationship between two variables may change as a result of removing outliers.
Recall that in the baseball example earlier in the chapter, most of the points were clustered in the lower left corner of the plot, making it difficult to see the general pattern of the majority of the data. This difficulty was caused by a few outlying players whose on-base percentages (OBPs) were exceptionally high. These values are present in our dataset only because these players had very few batting opportunities.
Both OBP and SLG are known as rate statistics, since they measure the frequency of certain events (as opposed to their count). In order to compare these rates sensibly, it makes sense to include only players with a reasonable number of opportunities, so that these observed rates have the chance to approach their long-run frequencies.
In Major League Baseball, batters qualify for the batting title only if they have 3.1 plate appearances per game. This translates into roughly 502 plate appearances in a 162-game season. The mlbBat10 dataset does not include plate appearances as a variable, but we can use at-bats (AB) – which constitute a subset of plate appearances – as a proxy.
# Filter for AB greater than or equal to 200
ab_gt_200 <- mlbBat10 %>%
filter(AB >= 200)
# Scatterplot of SLG vs. OBP
ggplot(ab_gt_200, aes(x = OBP, y = SLG)) +
geom_point()
# Identify the outlying player
ab_gt_200 %>%
filter(OBP < 0.200)
The cor(x, y) function will compute the Pearson product-moment correlation between variables, x and y. Since this quantity is symmetric with respect to x and y, it doesn’t matter in which order you put the variables.
At the same time, the cor() function is very conservative when it encounters missing data (e.g. NAs). The use argument allows you to override the default behavior of returning NA whenever any of the values encountered is NA. Setting the use argument to “pairwise.complete.obs” allows cor() to compute the correlation coefficient for those observations where the values of x and y are both not missing.
# Compute correlation
ncbirths %>%
summarize(N = n(), r = cor(weight, mage))
# Compute correlation for all non-missing pairs
ncbirths %>%
summarize(N = n(), r = cor(weight, mage, use = "pairwise.complete.obs"))
In 1973, Francis Anscombe famously created four datasets with remarkably similar numerical properties, but obviously different graphic relationships. The Anscombe dataset contains the x and y coordinates for these four datasets, along with a grouping variable, set, that distinguishes the quartet.
It may be helpful to remind yourself of the graphic relationship by viewing the four scatterplots:
Anscombe <- readRDS("anscombe.rds")
ggplot(data = Anscombe, aes(x = x, y = y)) +
geom_point() +
facet_wrap(~ set)
# Compute properties of Anscombe
Anscombe %>%
group_by(set) %>%
summarize(
N = n(),
mean_of_x = mean(x),
std_dev_of_x = sd(x),
mean_of_y = mean(y),
std_dev_of_y = sd(y),
correlation_between_x_and_y = cor(x, y)
)
Note that all of the measures are identical (ignoring rounding error) across the four different sets.
Estimating the value of the correlation coefficient between two quantities from their scatterplot can be tricky. Statisticians have shown that people’s perception of the strength of these relationships can be influenced by design choices like the x and y scales.
# Run this and look at the plot
ggplot(data = mlbBat10, aes(x = OBP, y = SLG)) +
geom_point()
# Correlation for all baseball players
mlbBat10 %>%
summarize(N = n(), r = cor(OBP, SLG))
# Run this and look at the plot
mlbBat10 %>%
filter(AB > 200) %>%
ggplot(aes(x = OBP, y = SLG)) +
geom_point()
# Correlation for all players with at least 200 ABs
mlbBat10 %>%
filter(AB >= 200) %>%
summarize(N = n(), r = cor(x = OBP, y = SLG))
# Run this and look at the plot
ggplot(data = bdims, aes(x = hgt, y = wgt, color = factor(sex))) +
geom_point()
# Correlation of body dimensions
bdims %>%
group_by(sex) %>%
summarize(N = n(), r = cor(hgt, wgt))
# Run this and look at the plot
ggplot(data = mammals, aes(x = BodyWt, y = BrainWt)) +
geom_point() + scale_x_log10() + scale_y_log10()
# Correlation among mammals, with and without log
mammals %>%
summarize(N = n(),
r = cor(BodyWt, BrainWt),
r_log = cor(log(BodyWt), log(BrainWt)))
High correlation does not imply causation.
Statisticians must always be skeptical of potentially spurious correlations. Human beings are very good at seeing patterns in data, sometimes when the patterns themselves are actually just random noise. To illustrate how easy it can be to fall into this trap, we will look for patterns in truly random data.
The noise dataset contains 20 sets of x and y variables drawn at random from a standard normal distribution. Each set, denoted as z, has 50 observations of x, y pairs. Do you see any pairs of variables that might be meaningfully correlated? Are all of the correlation coefficients close to zero?
noise <- readRDS("noise.rds")
# Create faceted scatterplot
ggplot(noise, aes(x, y)) +
geom_point() +
facet_wrap(~z)
# Compute correlations for each dataset
noise_summary <- noise %>%
group_by(z) %>%
summarize(N = n(), spurious_cor = cor(x, y))
# Isolate sets with correlations above 0.2 in absolute strength
noise_summary %>%
filter((spurious_cor) > 0.2)
The simple linear regression model for a numeric response as a function of a numeric explanatory variable can be visualized on the corresponding scatterplot by a straight line. This is a “best fit” line that cuts through the data in a way that minimizes the distance between the line and the data points.
We might consider linear regression to be a specific example of a larger class of smooth models. The geom_smooth() function allows you to draw such models over a scatterplot of the data itself. This technique is known as visualizing the model in the data space. The method argument to geom_smooth() allows you to specify what class of smooth model you want to see. Since we are exploring linear models, we’ll set this argument to the value “lm”.
Note that geom_smooth() also takes an se argument that controls the standard error, which we will ignore for now.
# Scatterplot with regression line
ggplot(data = bdims, aes(x = hgt, y = wgt)) +
geom_point( ) +
geom_smooth(method = "lm", se = FALSE)
The least squares criterion implies that the slope of the regression line is unique. In practice, the slope is computed by R. In this exercise, we will experiment with trying to find the optimal value for the regression slope for weight as a function of height in the bdims dataset via trial-and-error.
To help, we’ve built a custom function for you called add_line(), which takes a single argument: the proposed slope coefficient.
add_line <- function(my_slope){
bdims_summary <- bdims %>%
summarize(N = n(), r = cor(hgt, wgt),
mean_hgt = mean(hgt), mean_wgt = mean(wgt),
sd_hgt = sd(hgt), sd_wgt = sd(wgt)) %>%
mutate(true_slope = r * sd_wgt / sd_hgt,
true_intercept = mean_wgt - true_slope * mean_hgt)
p <- ggplot(data = bdims, aes(x = hgt, y = wgt)) +
geom_point() +
geom_point(data = bdims_summary,
aes(x = mean_hgt, y = mean_wgt),
color = "red", size = 3)
my_data <- bdims_summary %>%
mutate(my_slope = my_slope,
my_intercept = mean_wgt - my_slope * mean_hgt)
p + geom_abline(data = my_data,
aes(intercept = my_intercept, slope = my_slope), color = "dodgerblue")
}
# Estimate optimal value of my_slope
add_line(my_slope = 1)
\(Y = β_{0}+β_{1}⋅X+ϵ\), where \(ϵ∼N(0,σ_{ϵ})\).
Recall the simple linear regression model:
\(Y=b_{0}+b_{1}⋅X\)
Two facts enable you to compute the slope b1 and intercept b0 of a simple linear regression model from some basic summary statistics.
First, the slope can be defined as:
\(b_{1}=r_{X},_{Y}⋅\frac{s_{Y}}{s_{X}}\)
where \(r_{X},_{Y}\) represents the correlation (cor()) of \(X\) and \(Y\) and $sX and sY represent the standard deviation (sd()) of X and Y, respectively.
Second, the point (\(\tilde{x}\), \(\tilde{y}\)) is always on the least squares regression line, where \(\tilde{x}\) and \(\tilde{y}\) denote the average of x and y, respectively.
The bdims_summary data frame contains all of the information you need to compute the slope and intercept of the least squares regression line for body weight (\(Y\)) as a function of height (\(X\)). You might need to do some algebra to solve for \(b_{0}\)!
bdims_summary <- bdims %>%
summarize(N = n(), r = cor(hgt, wgt),
mean_hgt = mean(hgt), mean_wgt = mean(wgt),
sd_hgt = sd(hgt), sd_wgt = sd(wgt))
bdims_summary
# Add slope and intercept
bdims_summary %>%
mutate(slope = r*(sd_wgt/sd_hgt),
intercept = mean_wgt - (slope*mean_hgt))
Regression to the mean is a concept attributed to Sir Francis Galton. The basic idea is that extreme random observations will tend to be less extreme upon a second trial. This is simply due to chance alone. While “regression to the mean” and “linear regression” are not the same thing, we will examine them together.
One way to see the effects of regression to the mean is to compare the heights of parents to their children’s heights. While it is true that tall mothers and fathers tend to have tall children, those children tend to be less tall than their parents, relative to average. That is, fathers who are 3 inches taller than the average father tend to have children who may be taller than average, but by less than 3 inches.
The Galton_men and Galton_women datasets contain data originally collected by Galton himself in the 1880s on the heights of men and women, respectively, along with their parents’ heights.
Compare the slope of the regression line to the slope of the diagonal line. What does this tell you?
Galton_men <- readRDS("Galton_men.rds")
Galton_women <- readRDS("Galton_women.rds")
# Height of children vs. height of father
ggplot(data = Galton_men, aes(x = father, y = height)) +
geom_point() +
geom_abline(slope = 1, intercept = 0) +
geom_smooth(method = "lm", se = FALSE)
# Height of children vs. height of mother
ggplot(data = Galton_women, aes(x = mother, y = height)) +
geom_point() +
geom_abline(slope = 1, intercept = 0) +
geom_smooth(method = "lm", se = FALSE)
Because the slope of the regression line is smaller than 1 (the slope of the diagonal line) for both males and females, we can verify Sir Francis Galton’s regression to the mean concept!
In an opinion piece about nepotism published in The New York Times in 2015, economist Seth Stephens-Davidowitz wrote that:
“Regression to the mean is so powerful that once-in-a-generation talent basically never sires once-in-a-generation talent. It explains why Michael Jordan’s sons were middling college basketball players and Jakob Dylan wrote two good songs. It is why there are no American parent-child pairs among Hall of Fame players in any major professional sports league.”
The author is arguing that “Because of regression to the mean, an outstanding basketball player is likely to have sons that are good at basketball, but not as good as him.”
Recall that the fitted model for the poverty rate of U.S. counties as a function of high school graduation rate is:
\(\hat{poverty}=64.594−0.591⋅hs\_grad\)
Among U.S. counties, each additional percentage point increase in the high school graduation rate is associated with about a 0.591 percentage point decrease in the poverty rate.
A politician interpreting the relationship between poverty rates and high school graduation rates implores his constituents:
If we can lower the poverty rate by 59%, we’ll double the high school graduate rate in our county (i.e. raise it by 100%).
Which mistakes in interpretation has the politician made?
While the geom_smooth(method = “lm”) function is useful for drawing linear models on a scatterplot, it doesn’t actually return the characteristics of the model. As suggested by that syntax, however, the function that creates linear models is lm(). This function generally takes two arguments:
The lm() function return a model object having class “lm”. This object contains lots of information about your regression model, including the data used to fit the model, the specification of the model, the fitted values and residuals, etc.
# Linear model for weight as a function of height
lm(wgt ~ hgt, data = bdims)
Call:
lm(formula = wgt ~ hgt, data = bdims)
Coefficients:
(Intercept) hgt
-105.011 1.018
# Linear model for SLG as a function of OBP
lm(SLG ~ OBP, data = mlbBat10)
Call:
lm(formula = SLG ~ OBP, data = mlbBat10)
Coefficients:
(Intercept) OBP
0.009407 1.110323
# Log-linear model for body weight as a function of brain weight
lm(log(BodyWt) ~ log(BrainWt), data = mammals)
Call:
lm(formula = log(BodyWt) ~ log(BrainWt), data = mammals)
Coefficients:
(Intercept) log(BrainWt)
-2.509 1.225
In the previous examples, we fit two regression models:
\(\hat{wgt}=−105.011+1.018⋅hgt\)
and
\(\hat{SLG}=0.009+1.110⋅OBP\)
A person who is 170 cm tall is expected to weigh about 68 kg.
An “lm” object contains a host of information about the regression model that you fit. There are various ways of extracting different pieces of information.
The coef() function displays only the values of the coefficients. Conversely, the summary() function displays not only that information, but a bunch of other information, including the associated standard error and p-value for each coefficient, the \(R^{2}\), adjusted \(R^{2}\), and the residual standard error. The summary of an “lm” object in R is very similar to the output you would see in other statistical computing environments (e.g. Stata, SPSS, etc.)
mod <- lm(wgt ~ hgt, data = bdims)
# Show the coefficients
coef(mod)
(Intercept) hgt
-105.011254 1.017617
# Show the full output
summary(mod)
Call:
lm(formula = wgt ~ hgt, data = bdims)
Residuals:
Min 1Q Median 3Q Max
-18.743 -6.402 -1.231 5.059 41.103
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -105.01125 7.53941 -13.93 <2e-16 ***
hgt 1.01762 0.04399 23.14 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 9.308 on 505 degrees of freedom
Multiple R-squared: 0.5145, Adjusted R-squared: 0.5136
F-statistic: 535.2 on 1 and 505 DF, p-value: < 2.2e-16
Once we have fit a regression model, we are often interested in the fitted values (\(\hat{y}_{i}\)) and the residuals (\(e_{i}\)), where i indexes the observations. Recall that:
\(e_{i}=y_{i}−\hat{y}_{i}\)
The least squares fitting procedure guarantees that the mean of the residuals is zero (n.b., numerical instability may result in the computed values not being exactly zero). At the same time, the mean of the fitted values must equal the mean of the response variable.
We will confirm these two mathematical facts by accessing the fitted values and residuals with the fitted.values() and residuals() functions, respectively, for the following model:
# Mean of weights equal to mean of fitted values?
mean(bdims$wgt) == mean(fitted.values(mod))
[1] TRUE
# Mean of the residuals
mean(residuals(mod))
[1] -1.538036e-15
As you fit a regression model, there are some quantities (e.g. \(R^2\)) that apply to the model as a whole, while others apply to each observation (e.g. \(\hat{y}_{i}\)). If there are several of these per-observation quantities, it is sometimes convenient to attach them to the original data as new variables.
The augment() function from the broom package does exactly this. It takes a model object as an argument and returns a data frame that contains the data on which the model was fit, along with several quantities specific to the regression model, including the fitted values, residuals, leverage scores, and standardized residuals.
# Load broom
library(broom)
# Create bdims_tidy
bdims_tidy <- augment(mod)
# Glimpse the resulting data frame
glimpse(bdims_tidy)
Rows: 507
Columns: 9
$ wgt [3m[90m<dbl>[39m[23m 65.6, 71.8, 80.7, 72.6, 78.8, 74.8, 86.4, 78.4, 62.0…
$ hgt [3m[90m<dbl>[39m[23m 174.0, 175.3, 193.5, 186.5, 187.2, 181.5, 184.0, 184…
$ .fitted [3m[90m<dbl>[39m[23m 72.05406, 73.37697, 91.89759, 84.77427, 85.48661, 79…
$ .se.fit [3m[90m<dbl>[39m[23m 0.4320546, 0.4520060, 1.0667332, 0.7919264, 0.818347…
$ .resid [3m[90m<dbl>[39m[23m -6.4540648, -1.5769666, -11.1975919, -12.1742745, -6…
$ .hat [3m[90m<dbl>[39m[23m 0.002154570, 0.002358152, 0.013133942, 0.007238576, …
$ .sigma [3m[90m<dbl>[39m[23m 9.312824, 9.317005, 9.303732, 9.301360, 9.312471, 9.…
$ .cooksd [3m[90m<dbl>[39m[23m 5.201807e-04, 3.400330e-05, 9.758463e-03, 6.282074e-…
$ .std.resid [3m[90m<dbl>[39m[23m -0.69413418, -0.16961994, -1.21098084, -1.31269063, …
The fitted.values() function or the augment()-ed data frame provides us with the fitted values for the observations that were in the original data. However, once we have fit the model, we may want to compute expected values for observations that were not present in the data on which the model was fit. These types of predictions are called out-of-sample.
The ben data frame contains a height and weight observation for one person. The mod object contains the fitted model for weight as a function of height for the observations in the bdims dataset. We can use the predict() function to generate expected values for the weight of new individuals. We must pass the data frame of new observations through the newdata argument.
ben <- data.frame("wgt" = 74.8, "hgt" = 182.8)
# Print ben
ben
# Predict the weight of ben
predict(mod, ben)
1
81.00909
Note that the data frame ben has variables with the exact same names as those in the fitted model.
The geom_smooth() function makes it easy to add a simple linear regression line to a scatterplot of the corresponding variables. And in fact, there are more complicated regression models that can be visualized in the data space with geom_smooth(). However, there may still be times when we will want to add regression lines to our scatterplot manually. To do this, we will use the geom_abline() function, which takes slope and intercept arguments. Naturally, we have to compute those values ahead of time, but we already saw how to do this (e.g. using coef()).
The coefs data frame contains the model estimates retrieved from coef(). Passing this to geom_abline() as the data argument will enable you to draw a straight line on your scatterplot.
library(data.table)
coefs <- data.frame(coef(mod))
rnames <- rownames(coefs)
coefs <- coefs %>%
transpose()
colnames(coefs) <- rnames
# Add the line to the scatterplot
ggplot(data = bdims, aes(x = hgt, y = wgt)) +
geom_point() +
geom_abline(data = coefs,
aes(intercept = `(Intercept)`, slope = hgt),
color = "dodgerblue")
The residual standard error reported for the regression model for poverty rate of U.S. counties in terms of high school graduation rate is 4.67. What does this mean?
The typical difference between the observed poverty rate and the poverty rate predicted by the model is about 4.67 percentage points.
One way to assess strength of fit is to consider how far off the model is for a typical case. That is, for some observations, the fitted value will be very close to the actual value, while for others it will not. The magnitude of a typical residual can give us a sense of generally how close our estimates are.
However, recall that some of the residuals are positive, while others are negative. In fact, it is guaranteed by the least squares fitting procedure that the mean of the residuals is zero. Thus, it makes more sense to compute the square root of the mean squared residual, or root mean squared error (\(RMSE\)). R calls this quantity the residual standard error.
To make this estimate unbiased, you have to divide the sum of the squared residuals by the degrees of freedom in the model. Thus:
\(RMSE = \sqrt\frac{\sum_{i}e^2_{i}}{d.f}=\sqrt\frac{SSE}{d.f}\)
You can recover the residuals from mod with residuals(), and the degrees of freedom with df.residual().
# View summary of model
summary(mod)
Call:
lm(formula = wgt ~ hgt, data = bdims)
Residuals:
Min 1Q Median 3Q Max
-18.743 -6.402 -1.231 5.059 41.103
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -105.01125 7.53941 -13.93 <2e-16 ***
hgt 1.01762 0.04399 23.14 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 9.308 on 505 degrees of freedom
Multiple R-squared: 0.5145, Adjusted R-squared: 0.5136
F-statistic: 535.2 on 1 and 505 DF, p-value: < 2.2e-16
# Compute the mean of the residuals
mean(residuals(mod))
[1] -1.538036e-15
# Compute RMSE
sqrt(sum(residuals(mod)^2) / df.residual(mod))
[1] 9.30804
The coefficient of determination (\(R^2\)), can be computed as
\(R^2 = 1 − \frac{SSE}{SST} = 1 − \frac{Var(e)}{Var(y)}\)
where \(e\) is the vector of residuals and \(y\) is the response variable. This gives us the interpretation of \(R^2\) as the percentage of the variability in the response that is explained by the model, since the residuals are the part of that variability that remains unexplained by the model.
# View model summary
summary(mod)
Call:
lm(formula = wgt ~ hgt, data = bdims)
Residuals:
Min 1Q Median 3Q Max
-18.743 -6.402 -1.231 5.059 41.103
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -105.01125 7.53941 -13.93 <2e-16 ***
hgt 1.01762 0.04399 23.14 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 9.308 on 505 degrees of freedom
Multiple R-squared: 0.5145, Adjusted R-squared: 0.5136
F-statistic: 535.2 on 1 and 505 DF, p-value: < 2.2e-16
# Compute R-squared
bdims_tidy %>%
summarize(var_y = var(wgt), var_e = var(.resid)) %>%
mutate(R_squared = 1 - var_e / var_y)
This means that 51.4% of the variability in weight is explained by height.
The \(R^2\) reported for the regression model for poverty rate of U.S. counties in terms of high school graduation rate is 0.464.
lm(formula = poverty ~ hs_grad, data = countyComplete) %>%
summary()
Call:
lm(formula = poverty ~ hs_grad, data = countyComplete)
Residuals:
Min 1Q Median 3Q Max
-18.035 -3.034 -0.434 2.405 36.874
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 64.59437 0.94619 68.27 <2e-16 ***
hs_grad -0.59075 0.01134 -52.09 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 4.677 on 3141 degrees of freedom
Multiple R-squared: 0.4635, Adjusted R-squared: 0.4633
F-statistic: 2713 on 1 and 3141 DF, p-value: < 2.2e-16
How should this result be interpreted?
46.4% of the variability in poverty rate among U.S. counties can be explained by high school graduation rate.
The \(R^2\) gives us a numerical measurement of the strength of fit relative to a null model based on the average of the response variable:
\(\hat{y}_{null} = \overline{y}\)
This model has an \(R^2\) of zero because \(SSE = SST\). That is, since the fitted values (\(\hat{y}_{null}\)) are all equal to the average (\(\overline{y}\)), the residual for each observation is the distance between that observation and the mean of the response. Since we can always fit the null model, it serves as a baseline against which all other models will be compared.
mean(bdims_tidy$wgt)
[1] 69.14753
library(cowplot)
plot_null <- ggplot(data = bdims_tidy, aes(x = hgt, y = wgt)) +
geom_point() +
geom_abline(data = coefs,
aes(intercept = mean(bdims_tidy$wgt), slope = 0),
color = "dodgerblue")+
geom_segment(aes(x=hgt,y=wgt,xend=hgt,yend=mean(bdims_tidy$wgt)), color = "grey") +
ggtitle("null")
plot_lm <- ggplot(data = bdims_tidy, aes(x = hgt, y = wgt)) +
geom_point() +
geom_abline(data = coefs,
aes(intercept = `(Intercept)`, slope = hgt),
color = "dodgerblue")+
geom_segment(aes(x=hgt,y=wgt,xend=hgt,yend=.fitted), color = "grey") +
ggtitle("slr")
plot_grid(plot_null, plot_lm)
Use of `bdims_tidy$wgt` is discouraged. Use `wgt` instead.
# Compute SSE for null model
mod_null %>%
summarize(SSE = sum(.resid**2))
90123
# Compute SSE for regression model
mod_hgt %>%
summarize(SSE = sum(.resid**2))
43753
The leverage of an observation in a regression model is defined entirely in terms of the distance of that observation from the mean of the explanatory variable. That is, observations close to the mean of the explanatory variable have low leverage, while observations far from the mean of the explanatory variable have high leverage. Points of high leverage may or may not be influential.
The augment() function from the broom package will add the leverage scores (.hat) to a model data frame.
# Rank points of high leverage
mod %>%
augment() %>%
arrange(desc(.hat)) %>%
head()
As noted previously, observations of high leverage may or may not be influential. The influence of an observation depends not only on its leverage, but also on the magnitude of its residual. Recall that while leverage only takes into account the explanatory variable (\(x\)), the residual depends on the response variable (\(y\)) and the fitted value (\(\hat{y}\).
Influential points are likely to have high leverage and deviate from the general relationship between the two variables. We measure influence using Cook’s distance, which incorporates both the leverage and residual of each observation.
# Rank influential points
mod %>%
augment() %>%
arrange(desc(.cooksd)) %>%
head()
Observations can be outliers for a number of different reasons. Statisticians must always be careful—and more importantly, transparent—when dealing with outliers. Sometimes, a better model fit can be achieved by simply removing outliers and re-fitting the model. However, one must have strong justification for doing this. A desire to have a higher \(R^2\) is not a good enough reason!
In the mlbBat10 data, the outlier with an OBP of 0.550 is Bobby Scales, an infielder who had four hits in 13 at-bats for the Chicago Cubs. Scales also walked seven times, resulting in his unusually high OBP. The justification for removing Scales here is weak. While his performance was unusual, there is nothing to suggest that it is not a valid data point, nor is there a good reason to think that somehow we will learn more about Major League Baseball players by excluding him.
Nevertheless, we can demonstrate how removing him will affect our model.
# Create nontrivial_players
nontrivial_players <- mlbBat10 %>%
filter(AB >=10 &OBP < 0.500)
# Fit model to new data
mod_cleaner <- lm(SLG~OBP, nontrivial_players)
# View model summary
summary(mod_cleaner)
Call:
lm(formula = SLG ~ OBP, data = nontrivial_players)
Residuals:
Min 1Q Median 3Q Max
-0.31383 -0.04165 -0.00261 0.03992 0.35819
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.043326 0.009823 -4.411 1.18e-05 ***
OBP 1.345816 0.033012 40.768 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.07011 on 734 degrees of freedom
Multiple R-squared: 0.6937, Adjusted R-squared: 0.6932
F-statistic: 1662 on 1 and 734 DF, p-value: < 2.2e-16
# Visualize new model
ggplot(data = nontrivial_players, aes(x = OBP, y = SLG)) +
geom_point() +
geom_smooth(method = "lm")
Not all points of high leverage are influential. While the high leverage observation corresponding to Bobby Scales in the previous exercise is influential, the three observations for players with OBP and SLG values of 0 are not influential.
This is because they happen to lie right near the regression anyway. Thus, while their extremely low OBP gives them the power to exert influence over the slope of the regression line, their low SLG prevents them from using it.
# Rank high leverage points
mod %>%
augment() %>%
arrange(desc(.hat), (.cooksd)) %>%
head()