Week 7 Data Dive

In this weeks data dive, I will be testing two different null hypothesises, and I will visualize the results at the end.

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## âś” dplyr     1.1.2     âś” readr     2.1.4
## âś” forcats   1.0.0     âś” stringr   1.5.0
## âś” ggplot2   3.4.3     âś” tibble    3.2.1
## âś” lubridate 1.9.2     âś” tidyr     1.3.0
## âś” purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## âś– dplyr::filter() masks stats::filter()
## âś– dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggthemes)
library(ggrepel)
library(effsize)
library(pwrss)  
## 
## Attaching package: 'pwrss'
## 
## The following object is masked from 'package:stats':
## 
##     power.t.test
library(ggplot2)
cdata <- read.csv("/Users/cadgo/Downloads/data_aging_congress.csv")
cdf <- data.frame(cdata)
w7cdf <- cdf |>
  group_by(bioguide_id) |>
  mutate(years_in_congress_at_start = cmltv_cong*2 - 2,
         total_terms_in_congress = max(cmltv_cong),
         total_years_in_congress = total_terms_in_congress*2,
         before_2000 = floor(congress/107))
head(w7cdf)
## # A tibble: 6 Ă— 17
## # Groups:   bioguide_id [2]
##   congress start_date chamber state_abbrev party_code bioname        bioguide_id
##      <int> <chr>      <chr>   <chr>             <int> <chr>          <chr>      
## 1       82 1951-01-03 House   ND                  200 AANDAHL, Fred… A000001    
## 2       80 1947-01-03 House   VA                  100 ABBITT, Watki… A000002    
## 3       81 1949-01-03 House   VA                  100 ABBITT, Watki… A000002    
## 4       82 1951-01-03 House   VA                  100 ABBITT, Watki… A000002    
## 5       83 1953-01-03 House   VA                  100 ABBITT, Watki… A000002    
## 6       84 1955-01-03 House   VA                  100 ABBITT, Watki… A000002    
## # ℹ 10 more variables: birthday <chr>, cmltv_cong <int>, cmltv_chamber <int>,
## #   age_days <int>, age_years <dbl>, generation <chr>,
## #   years_in_congress_at_start <dbl>, total_terms_in_congress <int>,
## #   total_years_in_congress <dbl>, before_2000 <dbl>

First Null Hypothesis

The first null hypothesis I will be testing will be the following: The average age of congress after the year 2000 is equal to the average age of congress before 2000.

The last congress before 2000 was congress number 106. The first congress after 2000 is congress number 107

n1 <- w7cdf |>
    group_by(before_2000) |>
    summarize(sd = sd(age_years),
            mean = mean(age_years))

n1
## # A tibble: 2 Ă— 3
##   before_2000    sd  mean
##         <dbl> <dbl> <dbl>
## 1           0  10.5  52.7
## 2           1  10.9  57.5

The Observed difference will be calculated below.

odiff <- (n1$mean[2] - 
           n1$mean[1])
paste("Observed Difference: ", odiff)
## [1] "Observed Difference:  4.8004513715938"

With this in mind, we will perform a Neyman_Pearman hypothesis test. The code below will show the sampling distribution of the age differences.

bootstrap <- function (x, func=mean, n_iter=10^4) {
  func_values <- c(NULL)
  
  for (i in 1:n_iter) {
    x_sample <- sample_n(x, size = length(x), replace = TRUE)
    
    func_values <- c(func_values, func(x_sample))
  }
  
  return(func_values)
}
diff_avg <- function (w7cdf) {
  avg_ages <- w7cdf |>
    group_by(before_2000) |>
    summarize(avg_age = mean(age_years))
  
 
  diff_between <- (avg_ages$avg_age[2] - 
           avg_ages$avg_age[1])
  
  return(diff_between)
}

the_diff <- bootstrap(w7cdf, diff_avg, n_iter = 50)
ggplot() +
  geom_function(xlim = c(-5, 5),
                fun = function(x) dnorm(x, mean = 0, 
                                        sd = sd(the_diff))) +
  geom_vline(mapping = aes(xintercept = odiff,
                           color = paste("observed: ",
                                         round(odiff)))) +
  labs(title = "Bootstrapped Sampling Distribution of Age Differences",
       x = "Difference in Age Calculated",
       y = "Probability Density",
       color = "") +
  
  theme_minimal()

cohen.d(d = filter(w7cdf, before_2000 == 1) |> pluck("age_years"),
        f = filter(w7cdf, before_2000 == 0) |> pluck("age_years"))
## 
## Cohen's d
## 
## d estimate: 0.4539425 (small)
## 95 percent confidence interval:
##     lower     upper 
## 0.4261860 0.4816989

The above code gave me the Cohen’s D, where the d estimate gave me a number to represent the effect size. This number will be used as the delta in the code visualization below.

critical_value <- 2
delta <- 0.4539425

f_0 <- function(x) dnorm(x, mean = 0)
f_a <- function(x) dnorm(x, mean = delta)

ggplot() +
  stat_function(mapping = aes(fill = 'power'),
                fun = f_a, 
                xlim = c(critical_value, 4),
                geom = "area") +
    stat_function(mapping = aes(fill = 'alpha'),
                fun = f_0, 
                xlim = c(critical_value, 4),
                geom = "area") +
  geom_function(mapping = aes(color = 'Null Hypothesis'),
                xlim = c(-4, 4), fun = f_0) +
  geom_function(mapping = aes(color = 'Alternative Hypothesis'),
                xlim = c(-4, 4), fun = f_a) +
  geom_vline(mapping = aes(xintercept = critical_value,
                           color = "Critical Value")) +
  geom_vline(mapping = aes(xintercept = delta,
                           color = "Delta")) +
  geom_vline(mapping = aes(xintercept = 0),
             color = 'gray', linetype=2) +
  labs(title = "One-Tailed Test Illustration",
       subtitle = "(Mirror the right side for two-tailed tests.)",
       x = "Test Statistic",
       y = "Probability Density",
       color = "",
       fill = "") +
  scale_x_continuous(breaks = seq(-4, 4, 1)) +
  scale_fill_manual(values = c('lightblue', 'pink')) +
  scale_color_manual(values = c('darkred', 'darkorange', 'darkblue', 
                                'darkgreen')) +
  theme_minimal()

Now, here I would conduct a Fisher’s test, but the test would not make sense for my data and my null hypothesis. I do not have a success vs. non-success count total to compare for the test to represent any significance. Instead, I will just do a general p-value calculation.

the_diff_P <- the_diff - mean(the_diff)

paste("p-value ", 
      sum(odiff < the_diff_P) /
        length(the_diff_P))
## [1] "p-value  0"

Since the p-value is less than the significance level is chosen, we will reject the first null hypothesis.

Second Null Hypothesis

The second null hypothesis I will be testing will be the following: The average time served in congress after the year 2000 is equal to the average time served in congress before 2000.

n2 <- w7cdf |>
    group_by(before_2000) |>
    summarize(sd = sd(years_in_congress_at_start),
              mean = mean(years_in_congress_at_start))
n2
## # A tibble: 2 Ă— 3
##   before_2000    sd  mean
##         <dbl> <dbl> <dbl>
## 1           0  8.04  8.36
## 2           1  9.63 10.5

The Observed difference will be calculated below.

odiff2 <- (n2$mean[2] - 
           n2$mean[1])
paste("Observed Difference: ", odiff2)
## [1] "Observed Difference:  2.09585671529414"

With this in mind, we will perform a Neyman_Pearman hypothesis test. The code below will show the sampling distribution of the tenure differences.

diff_avg2 <- function (w7cdf) {
  avg_tenures <- w7cdf |>
    group_by(before_2000) |>
    summarize(avg_tenure = mean(years_in_congress_at_start))
  
 
  diff_between2 <- (avg_tenures$avg_tenure[2] - 
           avg_tenures$avg_tenure[1])
  
  return(diff_between2)
}

the_diff2 <- bootstrap(w7cdf, diff_avg2, n_iter = 50)
ggplot() +
  geom_function(xlim = c(-5, 5),
                fun = function(x) dnorm(x, mean = 0, 
                                        sd = sd(the_diff2))) +
  geom_vline(mapping = aes(xintercept = odiff2,
                           color = paste("observed: ",
                                         round(odiff2)))) +
  labs(title = "Bootstrapped Sampling Distribution of Tenure Differences",
       x = "Difference in Tenure Calculated",
       y = "Probability Density",
       color = "") +
  
  theme_minimal()

cohen.d(d = filter(w7cdf, before_2000 == 1) |> pluck("years_in_congress_at_start"),
        f = filter(w7cdf, before_2000 == 0) |> pluck("years_in_congress_at_start"))
## 
## Cohen's d
## 
## d estimate: 0.2488089 (small)
## 95 percent confidence interval:
##     lower     upper 
## 0.2212242 0.2763935

The above code gave me the Cohen’s D, where the d estimate gave me a number to represent the effect size. This number will be used as the delta in the code visualization below.

critical_value <- 2
delta <- 0.2488089

f_0 <- function(x) dnorm(x, mean = 0)
f_a <- function(x) dnorm(x, mean = delta)

ggplot() +
  stat_function(mapping = aes(fill = 'power'),
                fun = f_a, 
                xlim = c(critical_value, 4),
                geom = "area") +
    stat_function(mapping = aes(fill = 'alpha'),
                fun = f_0, 
                xlim = c(critical_value, 4),
                geom = "area") +
  geom_function(mapping = aes(color = 'Null Hypothesis'),
                xlim = c(-4, 4), fun = f_0) +
  geom_function(mapping = aes(color = 'Alternative Hypothesis'),
                xlim = c(-4, 4), fun = f_a) +
  geom_vline(mapping = aes(xintercept = critical_value,
                           color = "Critical Value")) +
  geom_vline(mapping = aes(xintercept = delta,
                           color = "Delta")) +
  geom_vline(mapping = aes(xintercept = 0),
             color = 'gray', linetype=2) +
  labs(title = "One-Tailed Test Illustration",
       subtitle = "(Mirror the right side for two-tailed tests.)",
       x = "Test Statistic",
       y = "Probability Density",
       color = "",
       fill = "") +
  scale_x_continuous(breaks = seq(-4, 4, 1)) +
  scale_fill_manual(values = c('lightblue', 'pink')) +
  scale_color_manual(values = c('darkred', 'darkorange', 'darkblue', 
                                'darkgreen')) +
  theme_minimal()

Here I will do a general p-value calculation.

the_diff_2 <- the_diff2 - mean(the_diff2)

paste("p-value ", 
      sum(odiff2 < the_diff_2) /
        length(the_diff_2))
## [1] "p-value  0"

Since the p-value is less than the significance level is chosen, we will reject the second null hypothesis.