Learning objectives

By the end of the lecture, you will be able to …

  • Use R to produce multivariate regression
  • Use R to create publication ready regression tables (e.g., Table 02)
  • Use R to produce \(R^2\) and interpret it

Packages

Load the standard packages and new package modelbased.

# install.packages("marginaleffects") # needed for modelbased
# install.packages("modelbased")

library(tidyverse) 
library(haven) # not core tidyverse
library(gssr)
library(gssrdoc)
library(summarytools)
library(gtsummary) 
library(modelbased)

# do not load moderndive(), use it specifically 

Load your data

# Load all gss
data(gss_all)

Variables

  • year Survey year
  • tvhours Hours per day watching tv
  • realrinc R’s income in constant $
  • age Age of respondent
  • educ Respondents highest edu credit
  • hrs1 How many hours did you work last week
  • childs How many children have you ever had?
  • polviews Think of self as liberal or conservative
  • sex Respondents sex
  • marital R’s marital status

Make a df with only the (pretty) categorical and continuous variables we’ll analyze.

# Categorical Variables
my_cat <- gss_all |>
  select(id, year, polviews, sex, marital) |>
  zap_missing() |>
  mutate(
    polviews = as_factor(polviews),
    sex = as_factor(sex),
    marital = as_factor(marital)) |> 
  droplevels()

# Continuous Variables
my_con <- gss_all |>
  select(id, year, tvhours, age, educ, hrs1, realrinc, childs) |>
  mutate(
    age = as.numeric(age),
    educ = as.numeric(educ),
    hrs1 = as.numeric(hrs1),
    realrinc = as.numeric(realrinc),
    childs = as.numeric(childs))

# Combine the two dataframes
my_data <- full_join(my_cat, my_con, by = c("year", "id")) # match by 2 vars

Two continuous variables

Simple Regression

model_01 <- lm(formula = childs ~ year, data = my_data)
moderndive::get_regression_table(model_01) 
# A tibble: 2 × 7
  term      estimate std_error statistic p_value lower_ci upper_ci
  <chr>        <dbl>     <dbl>     <dbl>   <dbl>    <dbl>    <dbl>
1 intercept   17.2       0.811      21.2       0   15.7     18.8  
2 year        -0.008     0         -18.9       0   -0.008   -0.007

Proportional Reduction of Error

The better a least-squares line is, the better it can predict an outcome with the least amount of error


\(r^2\) is a proportional reduction of error (PRE) measure


\(PRE = \frac{E1 - E2}{E1}\)


It tells us how well the regression model fits the data

\(R^2 = \frac{\sum E1^2 - \sum E2^2}{\sum E1^2}\)


E1
Errors of prediction made when IV is ignored


Equivalent to the sum of errors we would have if we guessed that every Y was equal to the mean of Y


aka Sum of Squares Total (SST)

E2
Errors of prediction made based on IV


Equivalent to the sum of errors we would have if we used our least squares line to predict Y


aka Sum of Squared Errors (SSE)

Use get_regression_points() to see E2.


model_01 <- lm(formula = childs ~ year, data = my_data)

moderndive::get_regression_points(model_01) |>
  dplyr::slice_sample(n = 5)  |>  # preview a random sample
  select(ID, year, childs, childs_hat, residual)
# A tibble: 5 × 5
     ID  year childs childs_hat residual
  <int> <dbl>  <dbl>      <dbl>    <dbl>
1 41065  2002      1       1.88   -0.885
2 64339  2018      0       1.76   -1.76 
3 32162  1994      2       1.95    0.053
4 47250  2006      3       1.86    1.14 
5 51810  2008      0       1.84   -1.84 

See E1 & E2

moderndive::get_regression_points(model_01) |>
  dplyr::mutate(
    mean_pred = mean(childs),
    E1 = (childs - mean_pred),
    E2 = residual) |>
  dplyr::slice_sample(n = 5) |>
  select(ID, year, childs,  mean_pred, childs_hat, E1, E2)
# A tibble: 5 × 7
     ID  year childs mean_pred childs_hat      E1     E2
  <int> <dbl>  <dbl>     <dbl>      <dbl>   <dbl>  <dbl>
1  2065  1973      2      1.91       2.11  0.0906 -0.108
2 47076  2006      1      1.91       1.86 -0.909  -0.855
3 12952  1982      2      1.91       2.04  0.0906 -0.039
4 32720  1996      0      1.91       1.93 -1.91   -1.93 
5 60392  2016      1      1.91       1.78 -0.909  -0.778

\(R^2\) ranges from 0 to 1.0


1.0 = Our independent variable accounts for all the variation that we find in the dependent variable (it predicts the dependent variable perfectly).


0.0 = Our independent variable does not improve our ability to predict the dependent variable.


In the social sciences, a high \(R^2\) is rare!

\(R^2\) calculation

my_test <- cor.test(
     ~ childs + year,
     data = my_data,
     method = "pearson",
     na.action = na.omit
 ) 

R

round(my_test$estimate, 3)
   cor 
-0.069 

\(R^2\)

round((my_test$estimate)^2, 3)
  cor 
0.005 

Use get_regression_summaries() to see \(R^2\).


model_01 <- lm(formula = childs ~ year, data = my_data)

moderndive::get_regression_summaries(model_01)
# A tibble: 1 × 9
  r_squared adj_r_squared   mse  rmse sigma statistic p_value    df  nobs
      <dbl>         <dbl> <dbl> <dbl> <dbl>     <dbl>   <dbl> <dbl> <dbl>
1     0.005         0.005  3.07  1.75  1.75      357.       0     1 75407


\(R^2\) shows the amount of variance of the DV explained by the IV(s).

\(R^2\) interpretation

An \(R^2\) of \(0.005\) means that knowing the survey year reduces our error in predicting average number of children by .5% compared with not using survey year at all.


The survey year explains .5% of variation in average number of children.

model_01 <- lm(formula = childs ~ year, data = my_data)
moderndive::get_regression_table(model_01)
# A tibble: 2 × 7
  term      estimate std_error statistic p_value lower_ci upper_ci
  <chr>        <dbl>     <dbl>     <dbl>   <dbl>    <dbl>    <dbl>
1 intercept   17.2       0.811      21.2       0   15.7     18.8  
2 year        -0.008     0         -18.9       0   -0.008   -0.007


model_02 <- lm(formula = childs ~ year + educ, data = my_data)
moderndive::get_regression_table(model_02)
# A tibble: 3 × 7
  term      estimate std_error statistic p_value lower_ci upper_ci
  <chr>        <dbl>     <dbl>     <dbl>   <dbl>    <dbl>    <dbl>
1 intercept    5.26      0.813      6.47   0        3.66     6.85 
2 year        -0.001     0         -2.00   0.045   -0.002    0    
3 educ        -0.131     0.002    -64.5    0       -0.134   -0.127

Change in PRE Measure

moderndive::get_regression_summaries(model_01)
# A tibble: 1 × 9
  r_squared adj_r_squared   mse  rmse sigma statistic p_value    df  nobs
      <dbl>         <dbl> <dbl> <dbl> <dbl>     <dbl>   <dbl> <dbl> <dbl>
1     0.005         0.005  3.07  1.75  1.75      357.       0     1 75407


moderndive::get_regression_summaries(model_02)
# A tibble: 1 × 9
  r_squared adj_r_squared   mse  rmse sigma statistic p_value    df  nobs
      <dbl>         <dbl> <dbl> <dbl> <dbl>     <dbl>   <dbl> <dbl> <dbl>
1     0.057         0.057  2.90  1.70  1.70     2266.       0     2 75166

tbl_regression()

OLS Regression predicting number of children by survey year and years of education

model_02 |>
  tbl_regression(intercept = TRUE)  
Characteristic Beta 95% CI p-value
(Intercept) 5.3 3.7, 6.9 <0.001
GSS year for this respondent 0.00 0.00, 0.00 0.045
educ -0.13 -0.13, -0.13 <0.001
Abbreviation: CI = Confidence Interval

tbl_regression()

OLS Regression predicting number of children by survey year and years of education

model_02 |>
  tbl_regression(
    intercept = TRUE) |>
  modify_column_hide(conf.low) |>
  modify_column_unhide(column = std.error) 
Characteristic Beta SE p-value
(Intercept) 5.3 0.813 <0.001
GSS year for this respondent 0.00 0.000 0.045
educ -0.13 0.002 <0.001
Abbreviations: CI = Confidence Interval, SE = Standard Error

tbl_regression()

OLS Regression predicting number of children by survey year and years of education

model_02 |>
  tbl_regression(
    intercept = TRUE) |>
  modify_column_hide(conf.low) |>
  modify_column_unhide(column = std.error) |>
  remove_abbreviation() |>
  add_significance_stars() |>
  add_glance_table(include = c("r.squared", "nobs"))
Characteristic Beta1 SE
(Intercept) 5.3*** 0.813
GSS year for this respondent 0.00* 0.000
educ -0.13*** 0.002
R² 0.057
No. Obs. 75,166
1 p<0.05; p<0.01; p<0.001

1 continuous variable & 1 categorical variable

tbl_regression()

OLS Regression predicting weekly work hours by years of education and gender

model |>
  tbl_regression(
    intercept = TRUE) |>
  modify_column_hide(conf.low) |>
  modify_column_unhide(
    column = std.error) |>
  remove_abbreviation() |>
  add_significance_stars() |>
  add_glance_table(
    include = c("r.squared", "nobs"))
Characteristic Beta1 SE
(Intercept) 39*** 0.320
educ 0.42*** 0.022
sex

    male — —
    female -6.6*** 0.132
R² 0.061
No. Obs. 43,167
1 p<0.05; p<0.01; p<0.001

tbl_regression()

OLS Regression predicting weekly work hours by years of education and gender

model |>
  tbl_regression(
    intercept = TRUE,
    show_single_row = sex,
    label = list(sex = "Women")) |>
  modify_column_hide(conf.low) |>
  modify_column_unhide(
    column = std.error) |>
  remove_abbreviation() |>
  add_significance_stars() |>
  add_glance_table(
    include = c("r.squared", "nobs"))
Characteristic Beta1 SE
(Intercept) 39*** 0.320
educ 0.42*** 0.022
Women -6.6*** 0.132
R² 0.061
No. Obs. 43,167
1 p<0.05; p<0.01; p<0.001

Regression Predicting Weekly Work Hours by Years of Education and Marital Status

model |>
  tbl_regression(
    intercept = TRUE,
    label = list(
      marital = "Marital status (ref. = married)")) |>
  remove_row_type(type = c("reference")) |>  
  modify_column_hide(conf.low) |>
  modify_column_unhide(
    column = std.error) |>
  remove_abbreviation() |>
  add_significance_stars() |>
  add_glance_table(
    include = c("r.squared", "nobs"))
Characteristic Beta1 SE
(Intercept) 37*** 0.330
educ 0.38*** 0.023
Marital status (ref. = married)

    widowed -5.9*** 0.385
    divorced 0.61** 0.198
    separated -0.28 0.379
    never married -1.8*** 0.163
R² 0.015
No. Obs. 43,178
1 p<0.05; p<0.01; p<0.001

# A tibble: 4 × 7
  term               estimate std_error statistic p_value lower_ci upper_ci
  <chr>                 <dbl>     <dbl>     <dbl>   <dbl>    <dbl>    <dbl>
1 intercept             5.00      0.056     89.1        0    4.89     5.12 
2 educ                 -0.159     0.004    -40.4        0   -0.166   -0.151
3 pol_group-Liberal     0.157     0.031      5.15       0    0.097    0.217
4 pol_group-Moderate    0.192     0.028      6.76       0    0.136    0.247

Change reference level

# Change to factor and change order
my_data$pol_group <- factor(
  my_data$pol_group,
  levels = c("Moderate", "Liberal", "Conservative"))

# OR ....

# change to factor and explicitly state reference category
my_data$pol_group <- relevel(factor(my_data$pol_group), 
                            ref = "Moderate")

table(my_data$pol_group)

    Moderate      Liberal Conservative 
       25140        18533        22205 

Change reference level

model <- lm(tvhours ~ educ + pol_group, data = my_data)
moderndive::get_regression_table(model)
# A tibble: 4 × 7
  term                   estimate std_error statistic p_value lower_ci upper_ci
  <chr>                     <dbl>     <dbl>     <dbl>   <dbl>    <dbl>    <dbl>
1 intercept                 5.20      0.054     96.4     0       5.09     5.30 
2 educ                     -0.159     0.004    -40.4     0      -0.166   -0.151
3 pol_group-Liberal        -0.035     0.03      -1.15    0.25   -0.093    0.024
4 pol_group-Conservative   -0.192     0.028     -6.76    0      -0.247   -0.136

Change reference level

model <- lm(tvhours ~ educ + relevel(pol_group, ref = "Liberal"), data = my_data)
moderndive::get_regression_table(model) 


term estimate std_error statistic p_value lower_ci upper_ci
intercept 5.162 0.059 88.013 0.00 5.047 5.277
educ -0.159 0.004 -40.421 0.00 -0.166 -0.151
relevel(pol_group, ref = “Liberal”)-Moderate 0.035 0.030 1.150 0.25 -0.024 0.093
relevel(pol_group, ref = “Liberal”)-Conservative -0.157 0.031 -5.148 0.00 -0.217 -0.097