# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer", "broom") # 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
## Loading required package: viridisLite
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following object is masked from 'package:purrr':
## 
##     compose
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[3]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [16] "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[7]]
##  [1] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
##  [6] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [11] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [16] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
##  [6] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[11]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "fst"          "RColorBrewer" "modelsummary" "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[12]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[13]]
##  [1] "infer"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
## [11] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[14]]
##  [1] "broom"        "infer"        "flextable"    "questionr"    "ggridges"    
##  [6] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
## [11] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [16] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [21] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"
ess <- read_fst("All-ESS-Data.fst")
uk_data <- ess%>%
filter(cntry == "GB") %>%
   mutate(
    gndr = case_when(
    gndr == 1 ~ 1,              
    gndr == 2 ~ 0,              
    gndr %in% c(9) ~ NA_real_,  
    TRUE ~ gndr               
  ),
  gndr = case_when(
      gndr %in% 1 ~ "Male",
      gndr %in% 0 ~ "Female",
      TRUE ~ as.character(gndr)
    ),
  lrscale = case_when(
      lrscale %in% 0:3 ~ "Left",
      lrscale %in% c(4, 5, 6) ~ "Center",
      lrscale %in% 7:10 ~ "Right",
      TRUE ~ as.character(lrscale)
    ),
   inctxff = case_when(
      inctxff %in% 1:2 ~ "Favour",
      inctxff %in% 3 ~ "Neutral",
      inctxff %in% 4:5 ~ "Oppose",
      TRUE ~ as.character(inctxff)
   ),
    lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
    inctxff = ifelse(inctxff %in% c(7, 8, 9), NA, inctxff),
  ecohenv = ifelse(ecohenv %in% c(7, 8, 9), NA, ecohenv),
  impenv = ifelse(impenv %in% c(6, 7, 8, 9), NA, impenv),
    impsafe = ifelse(impsafe %in% c(6, 7, 8, 9), NA, impsafe),
    wrclmch = ifelse(wrclmch %in% c(6, 7, 8, 9), NA, wrclmch),
    ccrdprs = ifelse(ccrdprs %in% c(77, 88, 99, 66), NA, ccrdprs)
   )
#Climate Change Attitude scale: '0' means not a climate scepsist
uk_data$climateatt <- scales::rescale(uk_data$impenv + 
                      uk_data$impsafe + 
                      uk_data$wrclmch + uk_data$ccrdprs,
                      to=c(0,100), na.rm=T)
class(uk_data$inctxff)
## [1] "character"
unique(uk_data$inctxff)
## [1] NA        "Oppose"  "Favour"  "Neutral"
class(uk_data$lrscale)
## [1] "character"
unique(uk_data$lrscale)
## [1] "Left"   "Center" "Right"  NA
# using unique to identify
unique(uk_data$gndr)
## [1] "Male"   "Female" NA
# does not return NA, but the following does
unique(uk_data$lrscale)
## [1] "Left"   "Center" "Right"  NA
# here's how to make sure it's really cleaned
uk_data <- uk_data %>% filter(!is.na(gndr))
uk_data <- uk_data %>% filter(!is.na(lrscale))
uk_data <- uk_data %>% filter(!is.na(inctxff))

# double-checking + quick distribution
unique(uk_data$lrscale)
## [1] "Right"  "Left"   "Center"
table(uk_data$lrscale)
## 
## Center   Left  Right 
##   1114    331    308
# Create a crosstable and save it into the object mytab
mytab <- table(uk_data$inctxff, uk_data$lrscale)

# 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]       [,3]
## [1,] 0.2218568 0.06591975 0.06133923
## [2,] 0.1616800 0.04803956 0.04470146
## [3,] 0.2519452 0.07485985 0.06965811
# Table of expected frequencies
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##         [,1]      [,2]      [,3]
## [1,] 388.915 115.55733 107.52767
## [2,] 283.425  84.21335  78.36167
## [3,] 441.660 131.22932 122.11067
# 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
# Step 1: Test statistic - Chi-Squared
test_stat <- uk_data %>%
  specify(explanatory = lrscale,  # Change variable name for the explanatory variable
          response = inctxff) %>%  # Change variable name for the outcome variable
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")  # Specify the appropriate test statistic

print(test_stat$stat)
## X-squared 
##   40.4649
# Step 2: Simulate the null distribution
null_distribution <- uk_data %>%
  specify(explanatory = lrscale,
          response = inctxff) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  calculate(stat = "chisq")
# Step 3: Calculate the p-value of your sample
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "greater") # would only replace test_stat if assigned another name in Step 1
## 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
# Step 4: Visualize
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

null_distribution 
## Response: inctxff (factor)
## Explanatory: lrscale (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 0.924
##  2         2 6.48 
##  3         3 4.39 
##  4         4 0.508
##  5         5 6.60 
##  6         6 3.62 
##  7         7 8.85 
##  8         8 4.01 
##  9         9 4.77 
## 10        10 1.97 
## # ℹ 990 more rows
#Under assumptions of frequentist hypothesis testing, reject the null.
conf_int <- null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")


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

null_distribution
## Response: inctxff (factor)
## Explanatory: lrscale (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 0.924
##  2         2 6.48 
##  3         3 4.39 
##  4         4 0.508
##  5         5 6.60 
##  6         6 3.62 
##  7         7 8.85 
##  8         8 4.01 
##  9         9 4.77 
## 10        10 1.97 
## # ℹ 990 more rows
uk_datan <- ess %>%
filter(cntry == "GB") %>%
   mutate(
    gndr = case_when(
    gndr == 1 ~ 1,              
    gndr == 2 ~ 0,              
    gndr %in% c(9) ~ NA_real_,  
    TRUE ~ gndr               
  ),
  gndr = case_when(
      gndr %in% 1 ~ "Male",
      gndr %in% 0 ~ "Female",
      TRUE ~ as.character(gndr)
    ),
  lrscale = case_when(
      lrscale %in% 0:3 ~ "Left",
      lrscale %in% c(4, 5, 6) ~ "Center",
      lrscale %in% 7:10 ~ "Right",
      TRUE ~ as.character(lrscale)
   ),
    lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
    inctxff = ifelse(inctxff %in% c(7, 8, 9), NA, inctxff),
  ecohenv = ifelse(ecohenv %in% c(7, 8, 9), NA, ecohenv),
  impenv = ifelse(impenv %in% c(6, 7, 8, 9), NA, impenv),
    impsafe = ifelse(impsafe %in% c(6, 7, 8, 9), NA, impsafe),
    wrclmch = ifelse(wrclmch %in% c(6, 7, 8, 9), NA, wrclmch),
    ccrdprs = ifelse(ccrdprs %in% c(77, 88, 99, 66), NA, ccrdprs)
   )
#Climate Change Attitude scale: '0' means not a climate scepsist
uk_data$climateatt <- scales::rescale(uk_data$impenv + 
                      uk_data$impsafe + 
                      uk_data$wrclmch + uk_data$ccrdprs,
                      to=c(0,100), na.rm=T)
class(uk_datan$inctxff)
## [1] "numeric"
unique(uk_datan$inctxff)
## [1] NA  5  2  1  3  4
models <- list(
"Model 1" <- lm(inctxff ~ lrscale, data = uk_datan),
"Model 2"<- lm(inctxff ~ lrscale + gndr, data = uk_datan),
"Model 3" <- lm(inctxff ~ lrscale + gndr + lrscale * gndr, data = uk_datan)

)
modelsummary(models)
 (1)   (2)   (3)
(Intercept) 3.175 3.158 3.183
(0.035) (0.042) (0.046)
lrscaleLeft −0.326 −0.327 −0.426
(0.072) (0.072) (0.097)
lrscaleRight 0.026 0.020 −0.023
(0.075) (0.075) (0.111)
gndrMale 0.040 −0.018
(0.056) (0.070)
lrscaleLeft × gndrMale 0.221
(0.146)
lrscaleRight × gndrMale 0.090
(0.151)
Num.Obs. 1753 1753 1753
R2 0.013 0.013 0.014
R2 Adj. 0.011 0.011 0.011
AIC 5492.7 5494.2 5495.8
BIC 5514.6 5521.6 5534.1
Log.Lik. −2742.360 −2742.107 −2740.917
RMSE 1.16 1.16 1.16
remotes::install_github("datalorax/equatiomatic")
## Skipping install of 'equatiomatic' from a github remote, the SHA1 (39e8c3ea) has not changed since last install.
##   Use `force = TRUE` to force installation
equatiomatic::extract_eq(`Model 3`, use_coefs = TRUE)

\[ \operatorname{\widehat{inctxff}} = 3.18 - 0.43(\operatorname{lrscale}_{\operatorname{Left}}) - 0.02(\operatorname{lrscale}_{\operatorname{Right}}) - 0.02(\operatorname{gndr}_{\operatorname{Male}}) + 0.22(\operatorname{lrscale}_{\operatorname{Left}} \times \operatorname{gndr}_{\operatorname{Male}}) + 0.09(\operatorname{lrscale}_{\operatorname{Right}} \times \operatorname{gndr}_{\operatorname{Male}}) \]