Installing packages + filtering for France

install.packages("fst", repos = "http://cran.us.r-project.org")
## Installing package into '/Users/lahughes/Library/R/arm64/4.2/library'
## (as 'lib' is unspecified)
## 
## The downloaded binary packages are in
##  /var/folders/2q/km873gjj6cl_h5x5r4_xlmj00000gq/T//RtmpMaB8Ii/downloaded_packages
library(fst)
ess <- read_fst("All-ESS-Data.fst")
france_data <- ess[ess$country == "France",]
france_data <- ess[ess$cntry == "FR",]
library(tidyverse)
## ── 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.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ 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

Looking into variable of interest (immigrants make country worse or better place to live/imwbcnt) in France + tidying up the outcome of interest.

france_data <- ess %>%
  filter(cntry == "FR") %>%
  mutate(
    imwbcnt = ifelse(imwbcnt %in% c(77,88,99), NA, imwbcnt),
  )

table(france_data$imwbcnt)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
## 1135  631 1342 1685 1861 6781 1693 1629 1164  342  490
library(modelsummary)
datasummary_skim(france_data$imwbcnt)
Unique (#) Missing (%) Mean SD Min Median Max
data 12 1 4.7 2.2 0.0 5.0 10.0

Re-coding education as a binary and numerical variable (having a bachelor’s degree (0 = BA) vs. not having a bachelor’s degree (1 = no-BA))

france_data <- france_data %>%
  mutate(
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ 0,
      essround >= 5 & edulvlb > 600 ~ 0,
      TRUE ~ 1
    )
  )

table(france_data$educ_level)
## 
##     0     1 
##  4235 14803
datasummary_skim(france_data$educ_level)
Unique (#) Missing (%) Mean SD Min Median Max
data 2 0 0.8 0.4 0.0 1.0 1.0

Re-coding place of residence (another predictor variable) into urban (=0), peri-urban (=1) and, rural (2), to understand how geographic location is a predictor of attitudes toward immigration and whether there is any interaction between education and place of residence when observing perspectives around immigration in France.

france_data <- france_data %>%
  mutate(geo = recode(as.character(domicil), 
                      '1' = 0, 
                      '2' = 1,
                      '3' = 2, 
                      '4' = 2, 
                      '5' = 2))
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `geo = recode(...)`.
## Caused by warning:
## ! Unreplaced values treated as NA as `.x` is not compatible.
## Please specify replacements exhaustively or supply `.default`.
table(france_data$geo)
## 
##     0     1     2 
##  3584  2361 13087
datasummary_skim(france_data$geo)
Unique (#) Missing (%) Mean SD Min Median Max
data 4 0 1.5 0.8 0.0 2.0 2.0
france_data <- france_data %>%
  filter(cntry == "FR") %>%
  mutate(
    geo = ifelse(geo %in% c(7,8,9), NA, geo),
  )
datasummary_skim(france_data %>% select(educ_level, geo, imwbcnt))
Unique (#) Missing (%) Mean SD Min Median Max
educ_level 2 0 0.8 0.4 0.0 1.0 1.0
geo 4 0 1.5 0.8 0.0 2.0 2.0
imwbcnt 12 1 4.7 2.2 0.0 5.0 10.0
packages <- c("tidyverse", "infer", "fst")
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

lapply(packages, library, character.only = TRUE)
## [[1]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "fstcore"      "fst"          "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[2]]
##  [1] "infer"        "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[3]]
##  [1] "infer"        "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"

Calculating the test statistic. I’m using the t-stat, because the two outcomes are both categorical.

france_data <- france_data %>%
  mutate(
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "NoBA"
    )
  )

test_stat <- france_data %>%
  specify(explanatory = educ_level,
          response = imwbcnt) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "t")
## Warning: Removed 285 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "NoBA", or divided in the order "BA" / "NoBA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "NoBA")` to
## the calculate() function.
print(test_stat$stat)
##        t 
## 32.25387

Calculating the null distribution.

null_distribution <- france_data %>%
  specify(explanatory = educ_level,
          response = imwbcnt) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% #
  calculate(stat = "t")
## Warning: Removed 285 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "NoBA", or divided in the order "BA" / "NoBA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "NoBA")` to
## the calculate() function.

P-value

p_val <- null_distribution %>%
  get_pvalue(obs_stat = test_stat, direction = "two-sided") 
## 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
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0

Simiulation-based null distribution

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

With confidence intervals

conf_int <- null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")


null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

model1 <- lm(imwbcnt ~ educ_level, data = france_data)
coefficients <- coef(model1)
print(coefficients)
##    (Intercept) educ_levelNoBA 
##       5.617103      -1.149248
packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "interactions") 

new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

lapply(packages, library, character.only = TRUE)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## Loading required package: grid
## Loading required package: Matrix
## 
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
## Loading required package: survival
## 
## Attaching package: 'survey'
## The following object is masked from 'package:graphics':
## 
##     dotchart
## [[1]]
##  [1] "infer"        "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[2]]
##  [1] "infer"        "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[3]]
##  [1] "infer"        "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[4]]
##  [1] "infer"        "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[5]]
##  [1] "effects"      "carData"      "infer"        "modelsummary" "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "fstcore"     
## [16] "fst"          "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "survey"       "survival"     "Matrix"       "grid"         "effects"     
##  [6] "carData"      "infer"        "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "fstcore"      "fst"         
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[7]]
##  [1] "interactions" "survey"       "survival"     "Matrix"       "grid"        
##  [6] "effects"      "carData"      "infer"        "modelsummary" "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "fstcore"     
## [21] "fst"          "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"

Regression model

model1 <- lm(imwbcnt ~ educ_level, data = france_data)
coefficients <- coef(model1)
print(coefficients)
##    (Intercept) educ_levelNoBA 
##       5.617103      -1.149248
modelsummary(
  list(model1),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)
educ_levelNoBA −1.1 (0.0)***
Num.Obs. 18753
R2 0.045
R2 Adj. 0.045
AIC 82604.6
BIC 82628.1
Log.Lik. −41299.306
RMSE 2.19

A visual

ggplot(france_data %>% 
         mutate(imwbcnt = ifelse(imwbcnt %in% c(77, 88), NA, imwbcnt)),
       aes(x = imwbcnt)) + 
  geom_histogram(binwidth = 1) +
  labs(title = "Histogram of Attitudes towards Immigrants in France", 
       x = "imwbcnt", 
       y = "Count")
## Warning: Removed 285 rows containing non-finite values (`stat_bin()`).

flextable::save_as_docx(table1, path = "summary_table1.docx",
                       width = 7.0, height = 7.0) 

```