R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

  1. Set up Environment
# List of packages
packages <- c("tidyverse", "infer", "fst") # add any you need here

# Install packages if they aren't installed already
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

# Load the packages
lapply(packages, library, character.only = TRUE)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ 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
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "infer"     "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"    
##  [7] "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"    
## [13] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "fst"       "infer"     "lubridate" "forcats"   "stringr"   "dplyr"    
##  [7] "purrr"     "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse"
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"
ess <- read_fst("All-ESS-Data.fst")

Task 1: Set up calculations for Switzerland for edulvlb and brncntr. Generate tables of expected proportions and frequencies. Determine and intepret the critcal value for independence. Determine and interpret both the Pearson’s chi-squared statistic and the p-value. Discuss main takeaways.

Filter data for Switzerland and recode for edulvlb and brncntr

switzerland_data <- ess %>%
  # Filter for Switzerland
  filter(cntry == "CH") %>%
  
  # Recoding clsprty and cleaning trstplt (will use later)
  mutate(
    clsprty = case_when(
      clsprty == 1 ~ "Yes",  # Recode 1 to "Yes"
      clsprty == 2 ~ "No",   # Recode 2 to "No"
      clsprty %in% c(7, 8, 9) ~ NA_character_,  # Handle other specific cases where you want to set it as NA
      TRUE ~ as.character(clsprty)  # Keep other values as-is but ensure they are characters
    ),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
    
    # Recoding education for rounds 1-4
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    # Re-coding education for rounds 5 and later
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    
    # Create educ_level column
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    ),
    
    # Recoding brncntr
   born_in_country = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_)
    
  )

Ensure that there are no NAs

unique(switzerland_data$brncntr)
## [1] 2 1 7 8
unique(switzerland_data$clsprty)
## [1] "Yes" "No"  NA
# here's how to make sure it's really cleaned
switzerland_data <- switzerland_data %>% filter(!is.na(clsprty))
switzerland_data <- switzerland_data %>% filter(!is.na(trstplt))
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))

# double-checking + quick distribution
unique(switzerland_data$clsprty)
## [1] "Yes" "No"
table(switzerland_data$clsprty)
## 
##   No  Yes 
## 7265 8866

Determine proportions and Frequencies

tab_dat <- switzerland_data

# Create a crosstable and save it into the object mytab
mytab <- table(tab_dat$brncntr, tab_dat$educ_level)

# Calculate row-wise sums of counts in table 
rsums <- rowSums(mytab)

# Calculate column-wise sums of counts in table
csums <- colSums(mytab)

# Get the total count of the table (N)
N <- sum(mytab)

# Generate table of expected proportions
ptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
##              [,1]         [,2]
## [1,] 1.811712e-01 6.061328e-01
## [2,] 4.893048e-02 1.637036e-01
## [3,] 1.426545e-05 4.772699e-05
#Print table of expected frequencies
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##              [,1]         [,2]
## [1,] 2922.4722584 9777.5277416
## [2,]  789.2976257 2640.7023743
## [3,]    0.2301159    0.7698841
# Determine critical value for independence
alpha <- 0.05 # significance level
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841

Calculate the Pearson’s chi-squared statistic

test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 68.5103

Calculate the p-value

p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(mytab, correct = F))
## Warning in chisq.test(mytab, correct = F): Chi-squared approximation may be
## incorrect
## 
##  Pearson's Chi-squared test
## 
## data:  mytab
## X-squared = 68.51, df = 2, p-value = 1.328e-15

Main Takeaway and Interpretations: Due to the Chi-squared test statistic not being greater than 3.841, we are rejecting the null hypothesis for the 0.05 significance level. This shows that there is a strong connection between the education level and the disparity between people born vs. not born in the country. For the Pearson’s chi-squared statistic test, our x-value (68.5103) is much greater than our critical value (3.841). This indicates that the disparity of whether or not one is born in Switzerland or not is closely associated with education level and whether or not someone has a BA. Our p-value, 1.328e-15 is close to 0, hence why it indicates that there is a strong connection between place of birth and education level. Because our chi-squared statistic is also a higher value, this confirms that there is no connection as well, as in order for there to be one, that value would be closer to 0. All in all, it can be concluded that we are able to reject the null hypothesis that being born in Switzerland is not associated with education level, as both variables are very dependent on one another and have a strong connection.

Task 2: Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for domicil (recoded as urban/rural – see tutorial 4) and gincdif (Government should reduce differences in income levels) for the country of Netherlands. For gincdif, you must recode for the five categories (i.e, cannot keep as numeric).

Recode and Mutate for gincdif and domicil

netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  mutate(geo = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Urban", 
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),
    
    gincdif = recode(as.character(gincdif), 
                      '1' = "Agree Strongly", 
                      '2' = "Agree", 
                      '3' = "Neither Agree nor Disagree", 
                      '4' = "Disagree", 
                      '5' = "Disagree Strongly",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_))

Step 1 - Calculate the test statistic of sample

test_stat <- netherlands_data %>%
  specify(explanatory = geo, 
          response = gincdif) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq")
## Warning: Removed 198 rows containing missing values.
print(test_stat$stat)
## X-squared 
##  8.176048

Step 2 - Simulate the null distribution

null_distribution <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%  
  calculate(stat = "Chisq")
## Warning: Removed 198 rows containing missing values.

Step 3 - Calculate the p-value of the sample

p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "greater") 
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.085

Step 4 - Visualize

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater")

null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  4.89
##  2         2  8.44
##  3         3  3.48
##  4         4  2.22
##  5         5  3.07
##  6         6  1.94
##  7         7  4.13
##  8         8  1.02
##  9         9  2.53
## 10        10  1.01
## # ℹ 990 more rows

Interpretation: Step 1: The value for the test statistic sample of 8.17 is higher than the base critical value of 3.841, indicating that there is a possibility of a connection. Due to the t-statistic of 8.17 being a large value, it indicates that the belief regarding the government changing the differences in income levels depending on living region is very different. Depending on if one resides in an urban or rural area, the beliefs change. Step 3: The p-value is 0.088 which rounds up to 0.09. Since this value is greater than 0.05, we are unable to reject the null. Step 4: The test statistic and the null distribution are overlapping hence why we are unable to reject the null.The distribution also shows that the likelhood of both variables being independent is high. Main Takeaway: Since the p-value is greater than 0.05, we are unable to reject the null hypothesis, and the possibility of both variables not being dependent on each other is very high.

Task 3:

First, talk about a research question you would like to consider, which identifies a main relationship between an explanatory variable and an outcome variable. Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for your variables based on your research question. After conducting the 4 steps, interpret all the output and discuss your takeaways.

I have always felt that the people in my life have told me that as they went through school and learned more, the amount of information they heard about one’s living area influencing how educated they are was very high. One thing that I would like to investigate is whether or not education level (BA vs. No BA) is influenced by one’s place of residence in France

france_data <- ess %>%
  filter(cntry == "FR") %>%
  mutate(geo = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Urban", 
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),
         
    # Recoding education for rounds 1-4
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    # Re-coding education for rounds 5 and later
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    
    # Create educ_level column
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    )
  
    )

Step 1 - Calculate the test statistic of sample

test_stat_france <- france_data %>%
  specify(explanatory = geo, 
          response = edulvlb) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "F") 
## Warning: Removed 7389 rows containing missing values.
print(test_stat_france$stat)
## [1] 90.83967

Step 2 - Simulate the null distribution

null_distribution_france <- france_data %>%
  specify(explanatory = geo,
          response = edulvlb) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "F")
## Warning: Removed 7389 rows containing missing values.

Step 3 - Calculate the p-value of sample

p_val_france <- null_distribution_france %>% 
  get_pvalue(obs_stat = test_stat_france, direction = "greater")
## Warning: Please be cautious in reporting a p-value of 0. This result is an
## approximation based on the number of `reps` chosen in the `generate()` step.
## See `?get_p_value()` for more information.
p_val_france
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0

Step 4 - Visualize

null_distribution_france %>%
  visualize() +
  shade_p_value(obs_stat = test_stat_france, direction = "greater")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

null_distribution_france
## Response: edulvlb (numeric)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1 0.131 
##  2         2 1.43  
##  3         3 1.82  
##  4         4 6.93  
##  5         5 0.361 
##  6         6 0.160 
##  7         7 0.0735
##  8         8 0.920 
##  9         9 0.436 
## 10        10 0.0286
## # ℹ 990 more rows

Interpretations

Step 1: A t-statistic value of 90.8 is a really high value, indicating that there is a strong correlation between the influence that one’s place of residence has on their education level. It shows that whether or not one has a BA or not is influenced by the area they live in (Urban or Rural). Step 3: The p-value that was obtained is 0. Because this is less than 0.05, it can be inferred that there is more evidence and a higher likelihood for rejecting the null hypothesis. Step 4: The data is heavily skewed to the right, and the null distribution and t-statistic do not overlap, hence why we are able to reject the null. Main Takeaway: Since the t-statstic value of 90.8 is really high, and our p-value is 0, we can confidently infer that we can reject the null hypothesis. Since the null distribution and t-statistic are not overlapping as seen in the visual, we can further confirm that there is likely a strong connection between the two variables.