Today

 

Joining data

Logarithms

Moderation

Loading data

library(tidyverse)
library(broom)
library(janitor)

Often you have multiple sources of data that you want to use together

metro_2021_crime    <- 
  read_csv("https://clanfear.github.io/ioc_iqa/_data/metro_2021_crime.csv")
borough_deprivation <- 
  read_csv("https://clanfear.github.io/ioc_iqa/_data/borough_deprivation.csv")
borough_pop_density <- 
  read_csv("https://clanfear.github.io/ioc_iqa/_data/borough_pop_density.csv")
london_subregion    <- 
  read_csv("https://clanfear.github.io/ioc_iqa/_data/london_subregion.csv")

Taking a look

names(metro_2021_crime)
[1] "borough"                     
[2] "month"                       
[3] "antisocial_behaviour"        
[4] "burglary"                    
[5] "robbery"                     
[6] "violence_and_sexual_offences"
names(london_subregion)
[1] "subregion" "borough"  
names(borough_pop_density)
[1] "Borough" "Pop"     "Area"   
names(borough_deprivation)
[1] "borough"     "deprivation"
[3] "dep_score"  
dim(metro_2021_crime)
[1] 384   6

 

dim(london_subregion)
[1] 32  2
dim(borough_pop_density)
[1] 32  3
dim(borough_deprivation)
[1] 32  3

Joining concepts

We can join data frames using functions from {dplyr} (part of {tidyverse})

Before we use them, we need to think about how we want to join the data frames:

  • Which rows are we keeping from each data frame?

  • Which columns are we keeping from each data frame?

  • Which variables determine whether rows match?

Types of join

Given two dataframes, df_a and df_b, there are many ways to join them

The most commonly used:

  • Left Join: df_a |> left_join(df_b)

    • Keep all columns and rows from df_a
    • Keep all columns but only rows that match from df_b
  • Inner Join: df_a |> inner_join(df_b)

    • Keep all columns but only rows that match from df_a
    • Keep all columns but only rows that match from df_b
  • Full Join: df_a |> full_join(df_b)

    • Keep all columns and rows from df_a
    • Keep all columns and rows from df_b

Same names

If the joined data frames share some column names, they will automatically match on those columns

metro_2021_crime |>
  left_join(london_subregion) |> 
  glimpse()
Rows: 384
Columns: 7
$ borough                      <chr> "Barking and Dagenham", "Bark…
$ month                        <date> 2021-01-01, 2021-02-01, 2021…
$ antisocial_behaviour         <dbl> 688, 585, 600, 531, 469, 507,…
$ burglary                     <dbl> 87, 105, 81, 85, 106, 90, 75,…
$ robbery                      <dbl> 30, 50, 49, 40, 47, 46, 42, 3…
$ violence_and_sexual_offences <dbl> 469, 449, 561, 564, 589, 617,…
$ subregion                    <chr> "East", "East", "East", "East…

 

While it does not occur here, if joined columns have no data for a given row (e.g., in full or left joins), NA values will be created

Differing names

borough_pop_density has a different naming style (title case)

If matching variable names differ, you can specify what left side variable ("borough") matches the right side variable ("Borough")

metro_2021_crime |>
  left_join(borough_pop_density, by = c("borough"="Borough")) |>
  glimpse()
Rows: 384
Columns: 8
$ borough                      <chr> "Barking and Dagenham", "Bark…
$ month                        <date> 2021-01-01, 2021-02-01, 2021…
$ antisocial_behaviour         <dbl> 688, 585, 600, 531, 469, 507,…
$ burglary                     <dbl> 87, 105, 81, 85, 106, 90, 75,…
$ robbery                      <dbl> 30, 50, 49, 40, 47, 46, 42, 3…
$ violence_and_sexual_offences <dbl> 469, 449, 561, 564, 589, 617,…
$ Pop                          <dbl> 221495, 221495, 221495, 22149…
$ Area                         <dbl> 36.1, 36.1, 36.1, 36.1, 36.1,…

It is better, usually, to just fix the names before joining though!

Many joins, handle it

We can chain many joins in order—and here we clean_names() to fix the capitalized names ahead of time

metro_2021 <- metro_2021_crime |>
  left_join(london_subregion) |>
  left_join(borough_deprivation) |>
  left_join(borough_pop_density |> clean_names())
head(metro_2021, 3)
# A tibble: 3 × 11
  borough           month      antisocial_behaviour burglary robbery
  <chr>             <date>                    <dbl>    <dbl>   <dbl>
1 Barking and Dage… 2021-01-01                  688       87      30
2 Barking and Dage… 2021-02-01                  585      105      50
3 Barking and Dage… 2021-03-01                  600       81      49
# ℹ 6 more variables: violence_and_sexual_offences <dbl>,
#   subregion <chr>, deprivation <chr>, dep_score <dbl>, pop <dbl>,
#   area <dbl>

Some clean-up

Let’s do a little bit of data management while we’re at it

metro_2021 <- metro_2021 |>
  rename(violence = violence_and_sexual_offences,
         asb      = antisocial_behaviour) |>
  mutate(month    = lubridate::month(month),
         pop_den = (pop/1000)/area)

Things done:

  • Shorten a couple names for ease of use
  • Convert month to an integer using {lubridate}1
  • Create a population density (pop_den) in thousands per \(km^2\)

[1] {lubridate} is a great package for working with dates and times

Model from last time

We created a curve with a quadratic functional form of month

lm_sq <- 
  lm(violence ~ month + I(month^2), 
   data = metro_2021) 
lm_sq |> tidy() |> 
  select(term, estimate, std.error)
# A tibble: 3 × 3
  term        estimate std.error
  <chr>          <dbl>     <dbl>
1 (Intercept)   431.      33.6  
2 month          62.5     11.9  
3 I(month^2)     -4.01     0.889

This fits our data well, but has drawbacks:

  • Uses two parameters
  • Complicated interpretation

There are simpler—more restrictive—curves we can fit

Logarithms

One parameter curve

log() provides an alternative single parameter curve

lm_log <- lm(violence ~ log(month), 
   data = metro_2021)
lm_log |> tidy() |> 
  select(term, estimate, std.error)
# A tibble: 2 × 3
  term        estimate std.error
  <chr>          <dbl>     <dbl>
1 (Intercept)    513.       23.8
2 log(month)      64.3      13.1

In this case, it doesn’t look like a great fit

  • These models are not nested so they cannot be compared with anova()
  • We’ll see a tool to compare these shortly

But first, what is log() anyway?

Quick maths

Exponentiation, \({\color{#00BDB6}{b}}^{{\color{#DD3025}{n}}} = {\color{#FD8153}{x}}\), multiplies a number (the base, \({\color{#00BDB6}{b}}\)) by itself \({\color{#DD3025}{n}}\) times:

\[{\color{#00BDB6}{5}}^{{\color{#DD3025}{2}}} = {\color{#00BDB6}{5}} \times {\color{#00BDB6}{5}} = {\color{#FD8153}{25}}\]

Roots, \(\sqrt[{\color{#DD3025}{n}}]{{\color{#FD8153}{x}}} = {\color{#00BDB6}{b}}\), give the base you’d need to raise to power \({\color{#DD3025}{n}}\) to get \({\color{#FD8153}{x}}\):

\[\sqrt[{\color{#DD3025}{2}}]{{\color{#FD8153}{25}}} = {\color{#FD8153}{25}} / {\color{#00BDB6}{5}} = {\color{#00BDB6}{5}}\]

Logarithms, \(\log_{{\color{#00BDB6}{b}}}({\color{#FD8153}{x}}) = {\color{#DD3025}{n}}\), give the \({\color{#DD3025}{n}}\) to which you raise \({\color{#00BDB6}{b}}\) to get \({\color{#FD8153}{x}}\):

\[\log_{{\color{#00BDB6}{5}}}({\color{#FD8153}{25}}) = {\color{#DD3025}{2}}\]

To get 25, you raise 5 (the base) to the power of 2

The natural log

In statistics and maths, we often use Euler’s number (~2.718), \(e\), as a base

  • \(log_{e}(x)\) is the natural logarithm and \(e^n\) is the exponential function
  • log(x) is \(log_{e}(x)\) or \(ln(x)\) and exp(n) is \(e^n\)
  • log(exp(x)) and exp(log(x)) are both equal to x!

Natural logs

exp(1:3)
[1]  2.718282  7.389056 20.085537
curve(exp(x), from = 1, to = 3)

log(1:3)
[1] 0.0000000 0.6931472 1.0986123
curve(log(x), from = 1, to = 3)

These are useful because they produce curves with simple derivatives:

\[\frac{d}{dx}e^x = e^x\quad\quad\quad\quad \frac{d}{dx}log_e(x) = \frac{1}{x}\]

\(e^x\) is its own derivative even!

log(x) interpretation

lm_log |> coef()
(Intercept)  log(month) 
  513.19271    64.31455 

Natural logs allow for a special interpretation called an elasticity or partial elasticity

When only an independent variable is logged, we call it a level-log (partial elasticity) model:

  • Divide the \(x\) coefficient by 100 and it is the amount \(y\) differs due to a \(1\%\) difference in \(x\)1

  • A \(1\%\) increase in month2 is associated with .64 more violence

[1] More precisely: \(p\%\) higher \(x\) is associated with \(b * log(1 + \frac{p}{100})\) higher \(y\)

log(y) interpretation

lm(log(violence) ~ month, 
   data = metro_2021) |> coef()
(Intercept)       month 
 6.26043831  0.01777349 

You can also log the outcome

When only the dependent variable is logged, we call it a log-level (partial elasticity) model:

  • Multiply \(x\) coefficient by 100 and it is the percent \(y\) differs due to a difference in \(x\)1

  • An increase of 1 in month is associated with \(1.7\%\) higher violence

[1] This is approximate; the exact version is a \((e^{b}-1)*100\%\) difference in \(y\)

Log-log models

lm(log(violence) ~ log(month), 
   data = metro_2021) |> coef()
(Intercept)  log(month) 
  6.1909002   0.1111105 

If we log both \(x\) and \(y\) we get a log-log (elasticity) model

When both \(x\) and \(y\) are logged:

  • The \(x\) coefficient is the percent \(y\) differs due to a percent difference in \(x\)

  • A \(1\%\) increase in month is associated with a \(0.11\%\) increase in violence

Working with logs

By compressing higher values, they reduce skew

  • This tends to reduce heteroskedasticity
    • Heteroskedasticity is variance that differs across model predictions
    • It only impacts standard errors in standard linear models1
    • Correct with robust errors, functional form, or alternate estimators
  • Makes some models easier to estimate

Some warnings:

  • You can only take a log of a positive (non-zero) number!
    • Don’t just add 1 then log it!2
  • The curve is inflexible
  • The percentage interpretation is an approximation
    • Inaccurate for changes in \(x\) much smaller or greater than \(1\)

[1] It causes serious problems in many other types of models
[2] See Chen & Roth (2024) Logs with zeros? Some problems and solutions

Moderation

Using interaction terms

 

Moderation in all things is best, but it’s pretty hard to get excited about it. — Mason Cooley

Moderation

Moderation occurs when the association between \(x\) and \(y\) is different across values of another variable \(z\)

This implies a multiplicative relationship rather than just an additive one

  • Additive: \(y = b_1x + b_2z\)
  • Multiplicative: \(y = b_1x + b_2z + b_3\color{#DD3025}{xz}\)

Note that we obey hierarchy: Include \(x\) and \(z\) alone when using \(x*z\)1

[1] There are rare cases when you drop one or both first order terms

Moderation and DAGs

 

Moderation is not indicated by DAGs1

Moderation is a type of functional form like polynomials or logarithms

 

Arrows pointing to other arrows are sometimes used in path diagrams (e.g., for SEM) to indicate moderation but not DAGs

Visual moderation

Moderation produces different slopes for \(x\) at each value of \(z\)

For categorical \(z\), this may be seen with a regression line for each level of \(z\)

ggplot(metro_2021 , 
    aes(x     = pop_den, 
        y     = violence, 
        color = deprivation)) + 
  geom_point() + 
  geom_smooth(method = "lm")

pop_den has a negative slope only for “medium” deprivation boroughs

  • Crime is lower when population density is higher in boroughs with moderate deprivation
  • Crime is higher when population density is higher in boroughs with low or high deprivation

Moderation formula

We can fit a model with moderation by multiplying variables in the formula

lm_int <- lm(violence ~ deprivation*pop_den, data = metro_2021)
lm_int |> tidy() |> select(term, estimate, statistic)
# A tibble: 6 × 3
  term                      estimate statistic
  <chr>                        <dbl>     <dbl>
1 (Intercept)                 632.      15.0  
2 deprivationLow             -205.      -3.87 
3 deprivationMedium           318.       5.83 
4 pop_den                       6.38     1.80 
5 deprivationLow:pop_den        3.96     0.546
6 deprivationMedium:pop_den   -37.5     -7.16 

By default, it will obey hierarchy and include the first-order terms

Interpretation

Interactions need to be interpreted using (partial) derivatives like polynomials

\[y = 632 -205*depLow + 318*depMed + 6.4*popDen + \\ 4.0*depLow*popDen - 37*depMed*popDen\]

The estimated effect of pop_den is the partial derivative:

\[\beta_{dpopDen} = \frac{dviolence}{dpopDen} = 6.4 + 4*depLow -37*depMed\]

We can calculate the effect of pop_den when deprivation is…

\[\begin{align} \text{Low: } & \beta_{dpopDen} = 6.4 + 4*1 -37*0 =\hphantom{-} 10.4\\ \text{Moderate: } & \beta_{dpopDen} = 6.4 + 4*0 -37*1 = -30.6\\ \text{High: } & \beta_{dpopDen} = 6.4 + 4*0 -37*0 =\hphantom{-} 6.4 \end{align}\]

Specification test

You can test if an interaction is warranted, because the additive model is nested inside the interaction model:

lm_noint <- lm(violence ~ deprivation + pop_den, data = metro_2021)
anova(lm_int, lm_noint)
Analysis of Variance Table

Model 1: violence ~ deprivation * pop_den
Model 2: violence ~ deprivation + pop_den
  Res.Df     RSS Df Sum of Sq      F    Pr(>F)    
1    378 8227307                                  
2    380 9551609 -2  -1324301 30.422 5.614e-13 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Fitted values

lm_int |>
  augment() |>
  ggplot(
    aes(x = pop_den, 
        y = .fitted, 
        color = deprivation)) +
  geom_point() +
  geom_line()

 

The fitted values are still all along lines…

… but there’s a different line for each level of deprivation!

Wrap-up

  • That was the last new content of the term!

  • No reading

  • Last assignment

    • Posted soon