Recap

Common workflow:

  • Load pacman package, then use p_load() to install+load packages
  • Gather tidy data into a data frame or tibble
  • Data manipulation:
    • Select subsets of variables using select()
    • Filter observations using filter()
    • Edit existing variables or create new ones using mutate()
    • Order observations using arrange()
    • Slice data using group_by()
    • Summarize data using summarize()
    • Use the pipe operator %>% (available through tidyverse) or |> (available through base R)!
  • Plot data using tools provided by the ggplot2 package
  • Estimate linear regression models using lm()
  • Present output using modelsummary() (available through the modelsummary package)
  • Retrieve coefficient estimates, standard errors, etc. using summary()

Today we will draw upon many of the items in the above list, as we work through a regression analysis project together in a fresh .Rmd file.

Load Packages

Load the following packages:

  • tidyverse – this will be used for data manipulation, plotting, etc.
  • gapminder – provides us with data
  • modelsummary – gives us access to the modelsummary() function for presenting regression outputs
library(pacman)
p_load(tidyverse, gapminder, modelsummary)

Manipulate Data

Take a look at the first few observations of the gapminder dataset:

head(gapminder) 
## # A tibble: 6 x 6
##   country     continent  year lifeExp      pop gdpPercap
##   <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
## 1 Afghanistan Asia       1952    28.8  8425333      779.
## 2 Afghanistan Asia       1957    30.3  9240934      821.
## 3 Afghanistan Asia       1962    32.0 10267083      853.
## 4 Afghanistan Asia       1967    34.0 11537966      836.
## 5 Afghanistan Asia       1972    36.1 13079460      740.
## 6 Afghanistan Asia       1977    38.4 14880372      786.

Standardize the pop, lifeExp, and gdpPercap variables in gapminder by year, and store the resulting data frame in an object called data_df:

data_df <- gapminder |> 
            group_by(year) |>
            mutate(pop = (pop - mean(pop))/sd(pop),
                   lifeExp = (lifeExp - mean(lifeExp))/sd(lifeExp), 
                   gdpPercap = (gdpPercap - mean(gdpPercap))/sd(gdpPercap)) |>
            ungroup() 
head(data_df)
## # A tibble: 6 x 6
##   country     continent  year lifeExp    pop gdpPercap
##   <fct>       <fct>     <int>   <dbl>  <dbl>     <dbl>
## 1 Afghanistan Asia       1952   -1.66 -0.147    -0.316
## 2 Afghanistan Asia       1957   -1.73 -0.145    -0.352
## 3 Afghanistan Asia       1962   -1.79 -0.145    -0.447
## 4 Afghanistan Asia       1967   -1.85 -0.142    -0.574
## 5 Afghanistan Asia       1972   -1.89 -0.137    -0.568
## 6 Afghanistan Asia       1977   -1.88 -0.131    -0.781

Store observations from 1957 and 1997 into separate objects called data57_df and data97_df, respectively.

data57_df <- data_df %>%
              filter(year == 1957)

data97_df <- data_df %>%
              filter(year == 1997)

rm(data_df)

Print the first few observations of data57_df to make sure all has been done correctly.

head(data57_df)
## # A tibble: 6 x 6
##   country     continent  year lifeExp     pop gdpPercap
##   <fct>       <fct>     <int>   <dbl>   <dbl>     <dbl>
## 1 Afghanistan Asia       1957  -1.73  -0.145    -0.352 
## 2 Albania     Europe     1957   0.635 -0.264    -0.239 
## 3 Algeria     Africa     1957  -0.476 -0.130    -0.130 
## 4 Angola      Africa     1957  -1.59  -0.217    -0.0478
## 5 Argentina   Americas   1957   1.05   0.0129    0.259 
## 6 Australia   Oceania    1957   1.54  -0.138     0.674

Print the first few observations of data97_df to make sure all has been done correctly.

head(data97_df)
## # A tibble: 6 x 6
##   country     continent  year lifeExp     pop gdpPercap
##   <fct>       <fct>     <int>   <dbl>   <dbl>     <dbl>
## 1 Afghanistan Asia       1997  -2.01  -0.125     -0.831
## 2 Albania     Europe     1997   0.686 -0.265     -0.580
## 3 Algeria     Africa     1997   0.358 -0.0732    -0.422
## 4 Angola      Africa     1997  -2.08  -0.217     -0.670
## 5 Argentina   Americas   1997   0.715 -0.0198     0.185
## 6 Australia   Oceania    1997   1.20  -0.152      1.76

Plot Data

Let’s separately plot the cross-sections of lifeExp and pop for 1957 and 1997, respectively.

ggplot(data57_df, aes(x = pop, y = lifeExp)) +
    labs(title = "Year 1957") +
    geom_point() 

ggplot(data97_df, aes(x = pop, y = lifeExp))  +
    labs(title = "Year 1997") +
    geom_point() 

Are the above plots helpful? Not really – outliers in the pop dimension are stretching the plots and making them uninformative.

We can deal with this by removing such outliers from the plots. Make the same plots, but this time exclude the major outliers.

ggplot(data57_df %>% filter(abs(pop) < 3), aes(x = pop, y = lifeExp)) +
    labs(title = "Year 1957") +
    geom_point() 

ggplot(data97_df %>% filter(abs(pop) < 3), aes(x = pop, y = lifeExp))  +
    labs(title = "Year 1997") +
    geom_point() 

Is there any kind of clear relationship between pop and lifeExp?

Now let’s plot the cross-sectional relationship between pop and gdpPercap to see if there’s any evidence for an interesting relationship. Exclude the pop outliers once again, but also exclude gdpPercap outliers.

ggplot(data57_df %>% filter(abs(pop) < 3, abs(gdpPercap) < 3), aes(x = pop, y = gdpPercap)) +
    labs(title = "Year 1957") +
    geom_point() 

ggplot(data97_df %>% filter(abs(pop) < 3), aes(x = pop, y = gdpPercap))  +
    labs(title = "Year 1997") +
    geom_point() 

Is there any kind of clear relationship between pop and gdpPercap?

Finally, let’s plot the relationship between lifeExp and gdpPercap in 1957 and 1997, respectively, without excluding any outliers.

ggplot(data57_df %>% filter(abs(lifeExp) < 3, abs(gdpPercap) < 3), aes(x = gdpPercap, y = lifeExp)) +
    labs(title = "Year 1957") +
    geom_point() 

ggplot(data97_df %>% filter(abs(lifeExp) < 3, abs(gdpPercap) < 3), aes(x = gdpPercap, y = lifeExp))  +
    labs(title = "Year 1997") +
    geom_point() 

Is there any kind of clear relationship between lifeExp and gdpPercap?

Draw a line of best fit through the data in both plots. Remove the outlier in the 1957 plot.

ggplot(data57_df %>% filter(abs(lifeExp) < 3, abs(gdpPercap) < 3), aes(x = gdpPercap, y = lifeExp)) +
    labs(title = "Year 1957") +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE, color = "red")

ggplot(data97_df %>% filter(abs(lifeExp) < 3, abs(gdpPercap) < 3), aes(x = gdpPercap, y = lifeExp))  +
    labs(title = "Year 1997") +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE, color = "red")

Estimate Regression Models

Regress lifeExp on gdpPercap for the 1957 and 1997 samples separately:

mod57 <- lm(formula = lifeExp ~ gdpPercap, data = data57_df)
mod97 <- lm(formula = lifeExp ~ gdpPercap, data = data97_df)

Present the results of these regressions together in a table using modelsummary():

models <- list("Model '57" = mod57, "Model '97" = mod97)
modelsummary(models, stars = TRUE)
Model ’57 Model ’97
(Intercept) 0.000 0.000
(0.080) (0.060)
gdpPercap 0.304*** 0.704***
(0.081) (0.060)
Num.Obs. 142 142
R2 0.092 0.495
R2 Adj. 0.086 0.492
AIC 394.2 310.9
BIC 403.1 319.8
Log.Lik. -194.115 -152.464
F 14.229 137.290
RMSE 0.96 0.71
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

Test Hypotheses

Two-Sided Tests

First, let us manually test whether the effect of gdpPercap on lifeExp is nonzero with a 99% level of confidence for the ’57 and ’97 sample regressions. Note that this implies we must carry out a two-sided test on the \(\beta_1\) coefficient estimate in both models, with our test statistic distribution being the \(t\)-distribution.

  • \(H_0\): \(\beta_1 = 0\)
  • \(H_1\): \(\beta_1 \neq 0\)

Separately pass the ’57 and ’97 regression model outputs into summary(), and store as new objects modsum57 and modsum97, respectively.

modsum57 <- summary(mod57)
modsum97 <- summary(mod97)

Store the degrees of freedom of both regressions as objects dof57 and dof97, respectively. If these two values are the same, then just store them into an object called dof and remove dof57 and dof97 from the work environment.

dof57 <- modsum57$df[2] 
dof97 <- modsum97$df[2] 
if (dof57 == dof97){
  dof <- dof57 
  rm(dof57, dof97)
  print(dof) 
}
## [1] 140

Using the above degrees of freedom, store the \(t\)-stats associated with a two-sided \(p\)-value of 0.01 (99% level of confidence) for the ’57 and ’97 samples into objects t_double99_57 and t_double99_97, respectively.

t_double99_57 <- qt(0.995, dof)
t_double99_97 <- qt(0.995, dof)

Now store the \(t\)-stats associated with our desired test as objects t_57 and t_97, respectively:

t_57 <- (modsum57$coefficients[2,1] - 0) / modsum57$coefficients[2,2]
t_97 <- (modsum97$coefficients[2,1] - 0) / modsum97$coefficients[2,2]

Create objects test57 and test97 that take the value TRUE if the null hypothesis is rejected, and FALSE otherwise.

test57 <- abs(t_57) > t_double99_57
test97 <- abs(t_97) > t_double99_97

Print test57 and test97 in the console to see if the null hypothesis were rejected.

Suppose we want to conduct the same kind of test, but this time we want to check whether \(\beta_1 \neq 1\). Carry out the same process as above, but this time in a single code chunk. Note that you may reuse t_double99_57 and t_double99_97.

t_57 <- (modsum57$coefficients[2,1] - 1) / modsum57$coefficients[2,2]
t_97 <- (modsum97$coefficients[2,1] - 1) / modsum97$coefficients[2,2]
test57 <- abs(t_57) > t_double99_57
test97 <- abs(t_97) > t_double99_97

One-Sided Tests

Carry out the following test with a 95% level of confidence on both samples:

  • \(H_0\): \(\beta_1 \geq 1\)
  • \(H_1\): \(\beta_1 < 1\)
 # Save critical t-stat
t_less95 <- qt(0.05, dof)

# Create test t-stats 
t_57 <- (modsum57$coefficients[2,1] - 1) / modsum57$coefficients[2,2]
t_97 <- (modsum97$coefficients[2,1] - 1) / modsum97$coefficients[2,2]

# Compare test t-stats with critical t-stat
# (TRUE if null is rejected, FALSE otherwise)
test57 <- t_57 < t_less95
test97 <- t_97 < t_less95 

#
# Print 1957 test result
#
if (test57 == TRUE){
  print("For the 1957 sample, the null hypothesis is rejected with a 95% level of confidence.")
}else{
  print("For the 1957 sample, the null hypothesis cannot be rejected with a 95% level of confidence.")
}
## [1] "For the 1957 sample, the null hypothesis is rejected with a 95% level of confidence."
#
# Print 1997 test result
#
if (test97 == TRUE){
  print("For the 1997 sample, the null hypothesis is rejected with a 95% level of confidence.")
}else{
  print("For the 1997 sample, the null hypothesis cannot be rejected with a 95% level of confidence.")
}
## [1] "For the 1997 sample, the null hypothesis is rejected with a 95% level of confidence."

Carry out the following test with a 95% level of confidence on both samples:

  • \(H_0\): \(\beta_1 \leq -1\)
  • \(H_1\): \(\beta_1 > -1\)
t_greater95 <- qt(0.95, dof) # Save critical t-stat
t_57 <- (modsum57$coefficients[2,1] - (-1)) / modsum57$coefficients[2,2]
t_97 <- (modsum97$coefficients[2,1] - (-1)) / modsum97$coefficients[2,2]
test57 <- t_57 > t_greater95
test97 <- t_97 > t_greater95

#
# Print 1957 test result
#
if (test57 == TRUE){
  print("For the 1957 sample, the null hypothesis is rejected with a 95% level of confidence.")
}else{
  print("For the 1957 sample, the null hypothesis cannot be rejected with a 95% level of confidence.")
}
## [1] "For the 1957 sample, the null hypothesis is rejected with a 95% level of confidence."
#
# Print 1997 test result
#
if (test97 == TRUE){
  print("For the 1997 sample, the null hypothesis is rejected with a 95% level of confidence.")
}else{
  print("For the 1997 sample, the null hypothesis cannot be rejected with a 95% level of confidence.")
}
## [1] "For the 1997 sample, the null hypothesis is rejected with a 95% level of confidence."

Carry out the following test with a 99% level of confidence on both samples:

  • \(H_0\): \(\beta_1 \leq 0.5\)
  • \(H_1\): \(\beta_1 > 0.5\)
t_greater99 <- qt(0.99, dof)
t_57 <- (modsum57$coefficients[2,1] - (0.5)) / modsum57$coefficients[2,2]
t_97 <- (modsum97$coefficients[2,1] - (0.5)) / modsum97$coefficients[2,2]
test57 <- t_57 > t_greater99
test97 <- t_97 > t_greater99 

#
# Print 1957 test result
#
if (test57 == TRUE){
  print("For the 1957 sample, the null hypothesis is rejected with a 99% level of confidence.")
}else{
  print("For the 1957 sample, the null hypothesis cannot be rejected with a 99% level of confidence.")
}
## [1] "For the 1957 sample, the null hypothesis cannot be rejected with a 99% level of confidence."
#
# Print 1997 test result
#
if (test97 == TRUE){
  print("For the 1997 sample, the null hypothesis is rejected with a 99% level of confidence.")
}else{
  print("For the 1997 sample, the null hypothesis cannot be rejected with a 99% level of confidence.")
}
## [1] "For the 1997 sample, the null hypothesis is rejected with a 99% level of confidence."