Setting up the environment and preliminary code

Installing the packages

packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable", "equatiomatic", "broom", "forcats", "RColorBrewer", "viridis", "knitr", "ggridges", "sandwich")

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

lapply(packages, library, character.only = TRUE)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ 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
## 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
## 
## 
## 
## Attaching package: 'MASS'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     select
## 
## 
## 
## Attaching package: 'kableExtra'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## 
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following objects are masked from 'package:kableExtra':
## 
##     as_image, footnote
## 
## 
## The following object is masked from 'package:purrr':
## 
##     compose
## 
## 
## Loading required package: viridisLite
## [[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"     
## 
## [[4]]
##  [1] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "effects"      "carData"      "modelsummary" "fst"          "infer"       
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[6]]
##  [1] "survey"       "survival"     "Matrix"       "grid"         "effects"     
##  [6] "carData"      "modelsummary" "fst"          "infer"        "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[7]]
##  [1] "MASS"         "survey"       "survival"     "Matrix"       "grid"        
##  [6] "effects"      "carData"      "modelsummary" "fst"          "infer"       
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[8]]
##  [1] "kableExtra"   "MASS"         "survey"       "survival"     "Matrix"      
##  [6] "grid"         "effects"      "carData"      "modelsummary" "fst"         
## [11] "infer"        "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "flextable"    "kableExtra"   "MASS"         "survey"       "survival"    
##  [6] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [11] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [16] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [21] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "equatiomatic" "flextable"    "kableExtra"   "MASS"         "survey"      
##  [6] "survival"     "Matrix"       "grid"         "effects"      "carData"     
## [11] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [16] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [21] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [26] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[11]]
##  [1] "broom"        "equatiomatic" "flextable"    "kableExtra"   "MASS"        
##  [6] "survey"       "survival"     "Matrix"       "grid"         "effects"     
## [11] "carData"      "modelsummary" "fst"          "infer"        "lubridate"   
## [16] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [21] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [26] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [31] "base"        
## 
## [[12]]
##  [1] "broom"        "equatiomatic" "flextable"    "kableExtra"   "MASS"        
##  [6] "survey"       "survival"     "Matrix"       "grid"         "effects"     
## [11] "carData"      "modelsummary" "fst"          "infer"        "lubridate"   
## [16] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [21] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [26] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [31] "base"        
## 
## [[13]]
##  [1] "RColorBrewer" "broom"        "equatiomatic" "flextable"    "kableExtra"  
##  [6] "MASS"         "survey"       "survival"     "Matrix"       "grid"        
## [11] "effects"      "carData"      "modelsummary" "fst"          "infer"       
## [16] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [21] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [26] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [31] "methods"      "base"        
## 
## [[14]]
##  [1] "viridis"      "viridisLite"  "RColorBrewer" "broom"        "equatiomatic"
##  [6] "flextable"    "kableExtra"   "MASS"         "survey"       "survival"    
## [11] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [16] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [21] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [26] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [31] "utils"        "datasets"     "methods"      "base"        
## 
## [[15]]
##  [1] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "broom"       
##  [6] "equatiomatic" "flextable"    "kableExtra"   "MASS"         "survey"      
## [11] "survival"     "Matrix"       "grid"         "effects"      "carData"     
## [16] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [21] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [26] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [31] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[16]]
##  [1] "ggridges"     "knitr"        "viridis"      "viridisLite"  "RColorBrewer"
##  [6] "broom"        "equatiomatic" "flextable"    "kableExtra"   "MASS"        
## [11] "survey"       "survival"     "Matrix"       "grid"         "effects"     
## [16] "carData"      "modelsummary" "fst"          "infer"        "lubridate"   
## [21] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [26] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [31] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [36] "base"        
## 
## [[17]]
##  [1] "sandwich"     "ggridges"     "knitr"        "viridis"      "viridisLite" 
##  [6] "RColorBrewer" "broom"        "equatiomatic" "flextable"    "kableExtra"  
## [11] "MASS"         "survey"       "survival"     "Matrix"       "grid"        
## [16] "effects"      "carData"      "modelsummary" "fst"          "infer"       
## [21] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [26] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [31] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [36] "methods"      "base"

Load in the ESS dataset

ess <- read_fst("All-ESS-Data.fst")

Filtering for country and recoding the variables of interest

german_data <- ess %>%
  filter(cntry == "DE") %>% # Filtering to Germany

mutate(
  minority_immigration = recode(as.character(imdfetn),
                                '1' = "Allow many to come and live here",
                                '2' = "Allow some",
                                '3' = "Allow a few",
                                '4' = "Allow none",
                                '7' = NA_character_,
                                '8' = NA_character_,
                                '9' = NA_character_),
  
   born_in_country = recode(as.character(brncntr),
                  '1' = "Yes",
                  '2' = "No",
                  '7' = NA_character_,
                  '8' = NA_character_,
                  '9' = NA_character_),
  
  lr = recode(as.character(lrscale),
                       '0' = "Left",
                       '1' = "Left",
                       '2' = "Left",
                       '3' = "Left",
                       '4' = "Center",
                       '5' = "Center",
                       '6' = "Center",
                       '7' = "Right",
                       '8' = "Right",
                       '9' = "Right",
                       '10' = "Right",
                       '77' = NA_character_,
                       '88' = NA_character_,
                       '99' = NA_character_),
  )

Introduction

Hypotheses

Context

Creating a flextable (summary statistics)

german_table <- german_data %>%
  mutate(
    imdfetn = ifelse(imdfetn %in% c(7, 8, 9), NA, imdfetn),
    lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
    brncntr = ifelse(brncntr == 1, 2, ifelse(brncntr %in% c(7, 8, 9), NA, brncntr))
  )
summary_table <- datasummary_skim(german_table %>% dplyr::select(imdfetn, lrscale, brncntr), output = "flextable")
## Warning: The histogram argument is only supported for (a) output types "default",
##   "html", "kableExtra", or "gt"; (b) writing to file paths with extensions
##   ".html", ".jpg", or ".png"; and (c) Rmarkdown, knitr or Quarto documents
##   compiled to PDF (via kableExtra)  or HTML (via kableExtra or gt). Use
##   `histogram=FALSE` to silence this warning.
summary_table

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

imdfetn

5

2

2.2

0.8

1.0

2.0

4.0

lrscale

12

7

4.5

1.9

0.0

5.0

10.0

brncntr

2

0

2.0

0.0

2.0

2.0

2.0

Editing and saving flextable as .docx

german_data_v2 <- german_table %>%
  rename(
    `Allow minority race/ethnic group immigration` = imdfetn,
    `Placement on Left-Right Scale` = lrscale,
    `Born in Country` = brncntr
  )
summary_table_v2 <- datasummary_skim(german_data_v2 %>% dplyr::select(`Allow minority race/ethnic group immigration`, `Placement on Left-Right Scale`, `Born in Country`), output = "flextable")
## Warning: The histogram argument is only supported for (a) output types "default",
##   "html", "kableExtra", or "gt"; (b) writing to file paths with extensions
##   ".html", ".jpg", or ".png"; and (c) Rmarkdown, knitr or Quarto documents
##   compiled to PDF (via kableExtra)  or HTML (via kableExtra or gt). Use
##   `histogram=FALSE` to silence this warning.
summary_table_v2

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Allow minority race/ethnic group immigration

5

2

2.2

0.8

1.0

2.0

4.0

Placement on Left-Right Scale

12

7

4.5

1.9

0.0

5.0

10.0

Born in Country

2

0

2.0

0.0

2.0

2.0

2.0

set_flextable_defaults(fonts_ignore=TRUE)
print(summary_table_v2, preview = "pdf")
## a flextable object.
## col_keys: ` `, `Unique (#)`, `Missing (%)`, `Mean`, `SD`, `Min`, `Median`, `Max` 
## header has 1 row(s) 
## body has 3 row(s) 
## original dataset sample: 
##                                                Unique (#) Missing (%) Mean  SD
## 1 Allow minority race/ethnic group immigration          5           2  2.2 0.8
## 2                Placement on Left-Right Scale         12           7  4.5 1.9
## 3                              Born in Country          2           0  2.0 0.0
##   Min Median  Max
## 1 1.0    2.0  4.0
## 2 0.0    5.0 10.0
## 3 2.0    2.0  2.0

Findings

Calculating the test statistic

test_stat <- german_data %>%
  specify(explanatory = lrscale,
          response = imdfetn) %>%
calculate(stat = "slope")
print(test_stat$stat)
##    lrscale 
## 0.01023866

Simulating the null distribution

null_distribution <- german_data %>%
  specify(explanatory = lrscale,
          response = imdfetn) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "slope")

Calculating the p-value of the sample

p_value <- 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_value
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0

Visualizing the null distribution and confidence intervals (0.95) with linear regression

ci <- 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 = ci)

null_distribution
## Response: imdfetn (numeric)
## Explanatory: lrscale (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate       stat
##        <int>      <dbl>
##  1         1 -0.000137 
##  2         2  0.000361 
##  3         3 -0.000210 
##  4         4 -0.000201 
##  5         5  0.0000258
##  6         6  0.000700 
##  7         7  0.0000649
##  8         8 -0.000276 
##  9         9 -0.000149 
## 10        10 -0.000353 
## # ℹ 990 more rows

Regression modelling

german_data$weight <- german_data$weight * german_data$weight
model1 <- lm(imdfetn ~ lrscale, data = german_data, weights = weight)
model2 <- lm(imdfetn ~ lrscale + brncntr, data = german_data, weights = weight)
model3 <- lm(imdfetn ~ lrscale + lrscale:brncntr, data = german_data, weights = weight)

Model summary

modelsummary(
  list(model1, model2, model3),
  fmt = 1,
  estimate  = c("{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)
lrscale 0.0 (0.0)*** 0.0 (0.0)*** 0.0 (0.0)***
brncntr −0.2 (0.0)***
lrscale × brncntr 0.0 (0.0)***
Num.Obs. 3045 3045 3045
R2 0.012 0.024 0.032
R2 Adj. 0.012 0.024 0.032
AIC 14108.3 14073.0 14047.7
BIC 14126.4 14097.1 14071.7
Log.Lik. −7051.166 −7032.494 −7019.830
RMSE 1.04 1.05 1.05

More in-depth model summary

models <- list(
  "Model 1: Single" = lm(imdfetn ~ lrscale, data = german_data, weights = weight),
  "Model 2: Multivariate" = lm(imdfetn ~ lrscale + brncntr, data = german_data, weights = weight),
  "Model 3: Interaction" = lm(imdfetn ~ lrscale + lrscale:brncntr, data = german_data, weights = weight)
)

modelsummary(models, vcov = "robust")
Model 1: Single  Model 2: Multivariate  Model 3: Interaction
(Intercept) 2.295 2.562 2.293
(0.155) (0.222) (0.154)
lrscale 0.005 0.005 0.023
(0.004) (0.004) (0.011)
brncntr −0.240
(0.115)
lrscale × brncntr −0.016
(0.007)
Num.Obs. 3045 3045 3045
R2 0.012 0.024 0.032
R2 Adj. 0.012 0.024 0.032
AIC 14108.3 14073.0 14047.7
BIC 14126.4 14097.1 14071.7
Log.Lik. −7051.166 −7032.494 −7019.830
RMSE 1.04 1.05 1.05
Std.Errors HC3 HC3 HC3

Relabeling and adding title

modelsummary(models, fmt = 1,
  estimate  = c("{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_rename = c("lrscale" = "Left-Right Scale", "brncntr" = "Born in Country", "lrscale × brncntr" = "LR Scale × Born in Cntry"),
  title = 'Table 2. Regression models predicting immigration attitudes')
Table 2. Regression models predicting immigration attitudes
Model 1: Single  Model 2: Multivariate  Model 3: Interaction
(Intercept) 2.3 (0.0)*** 2.6 (0.1)*** 2.3 (0.0)***
Left-Right Scale 0.0 (0.0)*** 0.0 (0.0)*** 0.0 (0.0)***
Born in Country −0.2 (0.0)***
Left-Right Scale:Born in Country 0.0 (0.0)***
Num.Obs. 3045 3045 3045
R2 0.012 0.024 0.032
R2 Adj. 0.012 0.024 0.032
AIC 14108.3 14073.0 14047.7
BIC 14126.4 14097.1 14071.7
Log.Lik. −7051.166 −7032.494 −7019.830
RMSE 1.04 1.05 1.05