# List of packages
packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "aod", "interactions","sandwich", "forcats", "RColorBrewer", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "skimr", "RColorBrewer", "infer", "broom")

# 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.4     ✔ 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: 'aod'
## 
## 
## The following object is masked from 'package:survival':
## 
##     rats
## 
## 
## Loading required package: viridisLite
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following object is masked from 'package:purrr':
## 
##     compose
## 
## 
## Registered S3 methods overwritten by 'broom':
##   method            from  
##   tidy.glht         jtools
##   tidy.summary.glht jtools
## [[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] "aod"          "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] "interactions" "aod"          "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] "sandwich"     "interactions" "aod"          "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] "sandwich"     "interactions" "aod"          "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"        
## 
## [[12]]
##  [1] "RColorBrewer" "sandwich"     "interactions" "aod"          "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] "viridis"      "viridisLite"  "RColorBrewer" "sandwich"     "interactions"
##  [6] "aod"          "MASS"         "survey"       "survival"     "Matrix"      
## [11] "grid"         "effects"      "carData"      "modelsummary" "fst"         
## [16] "infer"        "lubridate"    "forcats"      "stringr"      "dplyr"       
## [21] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [26] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [31] "datasets"     "methods"      "base"        
## 
## [[14]]
##  [1] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "sandwich"    
##  [6] "interactions" "aod"          "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] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "RColorBrewer"
##  [6] "sandwich"     "interactions" "aod"          "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"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "RColorBrewer" "sandwich"     "interactions" "aod"          "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] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "RColorBrewer" "sandwich"     "interactions" "aod"          "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"        
## 
## [[18]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "RColorBrewer" "sandwich"     "interactions" "aod"         
## [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"        
## 
## [[19]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "RColorBrewer" "sandwich"     "interactions"
## [11] "aod"          "MASS"         "survey"       "survival"     "Matrix"      
## [16] "grid"         "effects"      "carData"      "modelsummary" "fst"         
## [21] "infer"        "lubridate"    "forcats"      "stringr"      "dplyr"       
## [26] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [31] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [36] "datasets"     "methods"      "base"        
## 
## [[20]]
##  [1] "skimr"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "sandwich"    
## [11] "interactions" "aod"          "MASS"         "survey"       "survival"    
## [16] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [21] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [26] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [31] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [36] "utils"        "datasets"     "methods"      "base"        
## 
## [[21]]
##  [1] "skimr"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "sandwich"    
## [11] "interactions" "aod"          "MASS"         "survey"       "survival"    
## [16] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [21] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [26] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [31] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [36] "utils"        "datasets"     "methods"      "base"        
## 
## [[22]]
##  [1] "skimr"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "sandwich"    
## [11] "interactions" "aod"          "MASS"         "survey"       "survival"    
## [16] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [21] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [26] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [31] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [36] "utils"        "datasets"     "methods"      "base"        
## 
## [[23]]
##  [1] "broom"        "skimr"        "flextable"    "questionr"    "ggridges"    
##  [6] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "RColorBrewer"
## [11] "sandwich"     "interactions" "aod"          "MASS"         "survey"      
## [16] "survival"     "Matrix"       "grid"         "effects"      "carData"     
## [21] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [26] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [31] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [36] "grDevices"    "utils"        "datasets"     "methods"      "base"
ess <- read_fst("All-ESS-Data.fst")
#Cleaning Dataset and Creating outcome varible
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:1 ~ "Far Left",
      lrscale %in% 2:3 ~ "Center Left",
      lrscale %in% c(4, 5, 6) ~ "Center",
      lrscale %in% 7:8 ~ "Center Right",
      lrscale %in% 9:10 ~ "Far 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),
  ccgdbd = ifelse(ccgdbd %in% c(66, 77, 88, 99), NA, ccgdbd),
  impenv = ifelse(impenv %in% c(6, 7, 8, 9), NA, impenv),
  impsafe = ifelse(impsafe %in% c(6, 7, 8, 9), NA, impsafe),
  ecohenv = ifelse(ecohenv %in% c(7, 8, 9), NA, ecohenv),
   )
#Climate Change Oppisition scale: higher values corresponds to greater opposition to climate change mitigation
uk_datan$climateatt <- scales::rescale(uk_datan$inctxff + 
                      uk_datan$impenv + uk_datan$impsafe + uk_datan$ccgdbd,
                      to=c(1,3), na.rm=T)
#Making sure it is cleaned properly 
unique(uk_datan$gndr)
## [1] "Male"   "Female" NA
unique(uk_datan$climateatt)
##  [1]       NA 1.736842 2.157895 2.263158 1.947368 1.631579 1.842105 2.052632
##  [9] 2.578947 2.473684 2.368421 1.315789 1.210526 1.526316 1.421053 1.000000
## [17] 2.684211 2.789474 1.105263 3.000000 2.894737
unique(uk_datan$lrscale)
## [1] "Center Left"  "Center"       "Center Right" NA             "Far Left"    
## [6] "Far Right"
uk_datan <- uk_datan %>% filter(!is.na(gndr))
uk_datan <- uk_datan %>% filter(!is.na(lrscale))
uk_datan <- uk_datan %>% filter(!is.na(climateatt))

unique(uk_datan$lrscale)
## [1] "Center Right" "Far Left"     "Center"       "Center Left"  "Far Right"
table(uk_datan$lrscale)
## 
##       Center  Center Left Center Right     Far Left    Far Right 
##         1061          239          238           72           53
#Try 1 at creating descriptive statics - Table 1
library(skimr)
summary_table <- skim(uk_datan [c("lrscale", "gndr", "climateatt")])

# Display the summary table
print(summary_table)
## ── Data Summary ────────────────────────
##                            Values                      
## Name                       uk_datan[c("lrscale", "gn...
## Number of rows             1663                        
## Number of columns          3                           
## _______________________                                
## Column type frequency:                                 
##   character                2                           
##   numeric                  1                           
## ________________________                               
## Group variables            None                        
## 
## ── Variable type: character ────────────────────────────────────────────────────
##   skim_variable n_missing complete_rate min max empty n_unique whitespace
## 1 lrscale               0             1   6  12     0        5          0
## 2 gndr                  0             1   4   6     0        2          0
## 
## ── Variable type: numeric ──────────────────────────────────────────────────────
##   skim_variable n_missing complete_rate mean    sd p0  p25  p50  p75 p100 hist 
## 1 climateatt            0             1 1.88 0.343  1 1.63 1.84 2.16    3 ▂▆▇▃▁
#Try 2 at Table 1 
library(dplyr) 
library(MASS) 
library(skimr)
library(flextable)

uk_datac <- uk_datan %>%
  rename(
    `Left-Right Scale` = lrscale,
    `Opposition Towards Climate Change Mitigation` = climateatt,
    `Gender` = gndr
  )

uk_summary_table <- datasummary_skim(
  uk_datac %>% 
    dplyr::select(`Left-Right Scale`, `Opposition Towards Climate Change Mitigation`, `Gender`), 
  title = "Table 1: Descriptive Statistics for Core Variables",
  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.
print(uk_summary_table)
## a flextable object.
## col_keys: ` `, `Unique (#)`, `Missing (%)`, `Mean`, `SD`, `Min`, `Median`, `Max` 
## header has 1 row(s) 
## body has 1 row(s) 
## original dataset sample: 
##                                                Unique (#) Missing (%) Mean  SD
## 1 Opposition Towards Climate Change Mitigation         20           0  1.9 0.3
##   Min Median Max
## 1 1.0    1.8 3.0
#Successful Try 3 - table 1 - Final version
library(dplyr) 
library(MASS) 

uk_data <- ess%>%
filter(cntry == "GB")


uk_data_table_subset <- uk_data%>%
  mutate(
    gndr = case_when(
    gndr == 1 ~ 1,              
    gndr == 2 ~ 0,              
    gndr %in% c(9) ~ NA_real_,  
    TRUE ~ gndr 
    ),
    
    lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
    gndr = ifelse(gndr %in% c(9), NA, gndr),
    inctxff = ifelse(inctxff %in% c(7, 8, 9), NA, inctxff),
    ccgdbd = ifelse(ccgdbd %in% c(66, 77, 88, 99), NA, ccgdbd),
    impenv = ifelse(impenv %in% c(6, 7, 8, 9), NA, impenv),
    impsafe = ifelse(impsafe %in% c(6, 7, 8, 9), NA, impsafe),
    ecohenv = ifelse(ecohenv %in% c(7, 8, 9), NA, ecohenv)
  ) 

uk_data_table_subset$climateatt <- scales::rescale(uk_data_table_subset$inctxff + 
                      uk_data_table_subset$impenv + uk_data_table_subset$impsafe + uk_data_table_subset$ccgdbd,
                      to=c(1,3), na.rm=T)

uk_data_v3 <- uk_data_table_subset %>%
  rename(
    `Left-Right Scale` = lrscale,
    `Gender` = gndr,
    `Opposition Towards Climate Change Mitigation` = climateatt,
  )

uk_summary_table <- datasummary_skim(uk_data_v3 %>% 
  dplyr::select( `Left-Right Scale`, `Gender`, `Opposition Towards Climate Change Mitigation`), 
  title = "Table 1: Descriptive Statistics for Core Variables",
  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.
uk_summary_table
Table 1: Descriptive Statistics for Core Variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Left-Right Scale

12

11

5.0

1.9

0.0

5.0

10.0

Gender

3

0

0.4

0.5

0.0

0.0

1.0

Opposition Towards Climate Change Mitigation

21

91

1.9

0.3

1.0

1.8

3.0

#Ridge Plot - compares the relationship between political ideology and attitudes towards climate change mitiation
uk_datan%>%
  filter(!is.na(lrscale), !is.na(climateatt)) %>%
  mutate(
    lrscale = case_when(
      lrscale %in% 0:1 ~ "Far Left",
       lrscale %in% 2:3 ~ "Center Left",
      lrscale %in% c(4, 5, 6) ~ "Center",
      lrscale %in% 7:8 ~ "Center Right",
      lrscale %in% 9:10 ~ "Far Right",
      TRUE ~ as.character(lrscale)
    )
  ) %>%
  ggplot(aes(x = climateatt, y = lrscale, fill = lrscale)) +
  geom_density_ridges() +
  labs(title = "Attitudes Towards Climate Change Mitigation",
       x = "Climate Change Mitigation Opposition Scale",
       y = "Political Ideology") +
  scale_fill_manual(name = "Political Ideology", values = c("Center Left" = "lightyellow", "Center Right" = "brown", "Center" = "white","Far Left" = "orange", "Far Right" = "darkred")) +
  coord_cartesian(xlim = c(1, 3)) + 
  theme_minimal()
## Picking joint bandwidth of 0.112

#Time Trend 
uk_datan %>%
   mutate(yrbrn = case_when(
    yrbrn %in% c(7777, 8888, 9999) ~ NA_integer_,
    TRUE ~ as.integer(yrbrn)
  )) %>% 
  group_by(yrbrn) %>%
  summarise(avg_climateatt= mean(climateatt, na.rm = TRUE)) %>%
  ggplot(aes(x = yrbrn, y = avg_climateatt)) +
  geom_line() + 
  labs(title = "Average Attitude towards Increasing Fossil Fuel Tax by Birth Year", 
       x = "Birth Year", y = "Average Climate Change Attitude" ) +
  xlim (1916,2002) +
  ylim (1,3) +
  theme_minimal()
## Warning: Removed 1 row containing missing values (`geom_line()`).

#Bivariate statistics - Column Percentages
table(uk_datan$lrscale, uk_datan$climateatt) %>%
 cprop()
##               
##                1     1.10526315789474 1.21052631578947 1.31578947368421
##   Center        20.0  50.0             51.6             50.0           
##   Center Left   20.0  36.4             29.0             22.6           
##   Center Right  20.0   4.5              3.2             12.9           
##   Far Left      20.0   9.1              6.5              9.7           
##   Far Right     20.0   0.0              9.7              4.8           
##   Total        100.0 100.0            100.0            100.0           
##               
##                1.42105263157895 1.52631578947368 1.63157894736842
##   Center        61.1             54.0             62.2           
##   Center Left   16.7             26.6             15.6           
##   Center Right  12.2              8.9             14.8           
##   Far Left       7.8              6.5              3.7           
##   Far Right      2.2              4.0              3.7           
##   Total        100.0            100.0            100.0           
##               
##                1.73684210526316 1.84210526315789 1.94736842105263
##   Center        65.2             66.4             69.4           
##   Center Left   15.8             14.1             10.8           
##   Center Right  12.5             13.6             15.1           
##   Far Left       5.4              4.1              2.7           
##   Far Right      1.1              1.8              2.2           
##   Total        100.0            100.0            100.0           
##               
##                2.05263157894737 2.15789473684211 2.26315789473684
##   Center        71.5             61.3             68.2           
##   Center Left    9.3             13.9              6.1           
##   Center Right  14.0             19.0             18.9           
##   Far Left       1.7              2.9              1.5           
##   Far Right      3.5              2.9              5.3           
##   Total        100.0            100.0            100.0           
##               
##                2.36842105263158 2.47368421052632 2.57894736842105
##   Center        62.3             73.9             60.7           
##   Center Left   10.1              6.5             14.3           
##   Center Right  20.3             17.4             10.7           
##   Far Left       4.3              2.2              7.1           
##   Far Right      2.9              0.0              7.1           
##   Total        100.0            100.0            100.0           
##               
##                2.68421052631579 2.78947368421053 2.89473684210526 3     All  
##   Center        36.4             83.3             50.0              0.0  63.8
##   Center Left    9.1              0.0              0.0              0.0  14.4
##   Center Right  27.3              0.0              0.0            100.0  14.3
##   Far Left       9.1              0.0             50.0              0.0   4.3
##   Far Right     18.2             16.7              0.0              0.0   3.2
##   Total        100.0            100.0            100.0            100.0 100.0
table(uk_datan$gndr, uk_datan$climateatt) %>%
 cprop()
##         
##          1     1.10526315789474 1.21052631578947 1.31578947368421
##   Female  60.0  50.0             58.1             53.2           
##   Male    40.0  50.0             41.9             46.8           
##   Total  100.0 100.0            100.0            100.0           
##         
##          1.42105263157895 1.52631578947368 1.63157894736842 1.73684210526316
##   Female  53.3             59.7             61.5             52.2           
##   Male    46.7             40.3             38.5             47.8           
##   Total  100.0            100.0            100.0            100.0           
##         
##          1.84210526315789 1.94736842105263 2.05263157894737 2.15789473684211
##   Female  50.9             55.4             60.5             58.4           
##   Male    49.1             44.6             39.5             41.6           
##   Total  100.0            100.0            100.0            100.0           
##         
##          2.26315789473684 2.36842105263158 2.47368421052632 2.57894736842105
##   Female  47.7             56.5             50.0             57.1           
##   Male    52.3             43.5             50.0             42.9           
##   Total  100.0            100.0            100.0            100.0           
##         
##          2.68421052631579 2.78947368421053 2.89473684210526 3     All  
##   Female  45.5             50.0              0.0              0.0  55.0
##   Male    54.5             50.0            100.0            100.0  45.0
##   Total  100.0            100.0            100.0            100.0 100.0
#Mean and standard deviation of climateatt when lrscale and gender are predictor variables
uk_datan %>%
  group_by(lrscale) %>%
  summarise(
    mean_climateatt = mean(climateatt, na.rm = TRUE),
    std_climateatt = sd(climateatt, na.rm = TRUE),
    
  )
## # A tibble: 5 × 3
##   lrscale      mean_climateatt std_climateatt
##   <chr>                  <dbl>          <dbl>
## 1 Center                  1.90          0.328
## 2 Center Left             1.76          0.345
## 3 Center Right            1.94          0.333
## 4 Far Left                1.77          0.399
## 5 Far Right               1.90          0.429
uk_datan %>%
  group_by(gndr) %>%
  summarise(
    mean_climateatt = mean(climateatt, na.rm = TRUE),
    std_climateatt = sd(climateatt, na.rm = TRUE)
  )
## # A tibble: 2 × 3
##   gndr   mean_climateatt std_climateatt
##   <chr>            <dbl>          <dbl>
## 1 Female            1.87          0.338
## 2 Male              1.89          0.349
#ESS Baseline comparisn 
library(dplyr)
library(tidyr)
library(ggplot2)

alless <- ess %>%
  mutate(
    lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
    inctxff = ifelse(inctxff %in% c(7, 8, 9), NA, inctxff),
    ccgdbd = ifelse(ccgdbd %in% c(66, 77, 88, 99), NA, ccgdbd),
    impenv = ifelse(impenv %in% c(6, 7, 8, 9), NA, impenv),
    impsafe = ifelse(impsafe %in% c(6, 7, 8, 9), NA, impsafe),
    ecohenv = ifelse(ecohenv %in% c(7, 8, 9), NA, ecohenv)
  )
alless$climateatt <- scales::rescale(alless$inctxff + 
                      alless$impenv + alless$impsafe + alless$ccgdbd,
                      to=c(1,3), na.rm=T)
  
avg_attitude_uk <- uk_datan %>%
  group_by(yrbrn) %>%
  summarize(mean_attitude_uk = mean(climateatt, na.rm = TRUE))

avg_attitude_all_countries <- alless %>%
  group_by(yrbrn) %>%
  summarize(mean_attitude_all = mean(climateatt, na.rm = TRUE))

combined_data <- left_join(avg_attitude_uk, avg_attitude_all_countries, by = "yrbrn")

long_data <- combined_data %>%
  pivot_longer(
    cols = starts_with("mean_attitude"),
    names_to = "Attitude_Type",
    values_to = "Mean_Attitude"
  )

ggplot(long_data) +
  geom_line(aes(x = yrbrn, y = Mean_Attitude, color = Attitude_Type), size = 1) +
  geom_point(aes(x = yrbrn, y = Mean_Attitude, color = Attitude_Type), size = 3) +
  labs(title = "Average Attitude Towards Climate Change Mitigation by Birth Year",
       x = "Year",
       y = "Mean Attitude ") +
  scale_color_manual(
    values = c("orange", "darkred"),
    name = "Dataset",
    labels = c("All ESS", "UK")
  ) +
  xlim(1980, 2002) +
  ylim(1, 3) +
  theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 120 rows containing missing values (`geom_line()`).
## Warning: Removed 120 rows containing missing values (`geom_point()`).

#Critical Value to determine significant or not 
uk_datac <- uk_datan %>%
  mutate(climateatt = case_when(
    climateatt %in% 1 ~ "Support",
    climateatt %in% 2 ~ "Neutral",
    climateatt %in% 3 ~ "Oppose",
    TRUE ~ as.character(climateatt)
  ))

#Testing the Null hypothesis - Critical Value
mytab <- table(uk_datac$climateatt, uk_datac$lrscale)

rsums <- rowSums(mytab)

csums <- colSums(mytab)

N <- sum(mytab)

ptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
##               [,1]         [,2]         [,3]         [,4]         [,5]
##  [1,] 0.0084402161 1.901236e-03 1.893281e-03 5.727574e-04 4.216131e-04
##  [2,] 0.0118930318 2.679015e-03 2.667805e-03 8.070672e-04 5.940911e-04
##  [3,] 0.0237860636 5.358029e-03 5.335611e-03 1.614134e-03 1.188182e-03
##  [4,] 0.0345281568 7.777785e-03 7.745242e-03 2.343098e-03 1.724781e-03
##  [5,] 0.0475721271 1.071606e-02 1.067122e-02 3.228269e-03 2.376365e-03
##  [6,] 0.0517922352 1.166668e-02 1.161786e-02 3.514647e-03 2.587171e-03
##  [7,] 0.0705908983 1.590125e-02 1.583472e-02 4.790334e-03 3.526218e-03
##  [8,] 0.0844021610 1.901236e-02 1.893281e-02 5.727574e-03 4.216131e-03
##  [9,] 0.0713581907 1.607409e-02 1.600683e-02 4.842403e-03 3.564547e-03
## [10,] 0.0659871441 1.486421e-02 1.480202e-02 4.477921e-03 3.296248e-03
## [11,] 0.0525595275 1.183952e-02 1.178998e-02 3.566716e-03 2.625499e-03
## [12,] 0.0506412966 1.140742e-02 1.135969e-02 3.436544e-03 2.529678e-03
## [13,] 0.0264715869 5.962968e-03 5.938019e-03 1.796375e-03 1.322332e-03
## [14,] 0.0176477246 3.975312e-03 3.958679e-03 1.197584e-03 8.815546e-04
## [15,] 0.0107420932 2.419755e-03 2.409631e-03 7.289639e-04 5.365984e-04
## [16,] 0.0042201081 9.506181e-04 9.466406e-04 2.863787e-04 2.108065e-04
## [17,] 0.0023018771 5.185190e-04 5.163494e-04 1.562066e-04 1.149854e-04
## [18,] 0.0007672924 1.728397e-04 1.721165e-04 5.206885e-05 3.832846e-05
## [19,] 0.0003836462 8.641983e-05 8.605824e-05 2.603443e-05 1.916423e-05
## [20,] 0.0019182309 4.320991e-04 4.302912e-04 1.301721e-04 9.582115e-05
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##              [,1]       [,2]       [,3]       [,4]       [,5]
##  [1,]  14.0360794  3.1617559  3.1485268 0.95249549 0.70114251
##  [2,]  19.7781118  4.4552014  4.4365604 1.34215274 0.98797354
##  [3,]  39.5562237  8.9104029  8.8731209 2.68430547 1.97594708
##  [4,]  57.4203247 12.9344558 12.8803367 3.89657246 2.86831028
##  [5,]  79.1124474 17.8208058 17.7462417 5.36861094 3.95189417
##  [6,]  86.1304871 19.4016837 19.3205051 5.84485869 4.30246542
##  [7,] 117.3926639 26.4437763 26.3331329 7.96632592 5.86410102
##  [8,] 140.3607937 31.6175586 31.4852676 9.52495490 7.01142514
##  [9,] 118.6686711 26.7312087 26.6193626 8.05291642 5.92784125
## [10,] 109.7366206 24.7191822 24.6157547 7.44678292 5.48165965
## [11,]  87.4064943 19.6891161 19.6067348 5.93144919 4.36620565
## [12,]  84.2164762 18.9705352 18.8911606 5.71497294 4.20685508
## [13,]  44.0222489  9.9164161  9.8749248 2.98737222 2.19903788
## [14,]  29.3481660  6.6109441  6.5832832 1.99158148 1.46602526
## [15,]  17.8641010  4.0240529  4.0072159 1.21226699 0.89236320
## [16,]   7.0180397  1.5808779  1.5742634 0.47624775 0.35057126
## [17,]   3.8280216  0.8622971  0.8586891 0.25977150 0.19122069
## [18,]   1.2760072  0.2874324  0.2862297 0.08659050 0.06374023
## [19,]   0.6380036  0.1437162  0.1431149 0.04329525 0.03187011
## [20,]   3.1900180  0.7185809  0.7155743 0.21647625 0.15935057
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_datac %>%
  specify(explanatory = lrscale,  # Change variable name for the explanatory variable
          response = climateatt) %>%  # Change variable name for the outcome variable
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")  # Specify the appropriate test statistic

print(test_stat$stat)
## X-squared 
##  141.2449
# Step 2: Simulate the null distribution
null_distribution <- uk_datac %>%
  specify(explanatory = lrscale,
          response = climateatt) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")
# Step 3: Calculate the p-value of your sample
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "greater")

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.001
# Step 4: Visualize 1
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater")

null_distribution 
## Response: climateatt (factor)
## Explanatory: lrscale (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  51.1
##  2         2  64.7
##  3         3  66.0
##  4         4 103. 
##  5         5  75.0
##  6         6  52.3
##  7         7  84.1
##  8         8  55.8
##  9         9  92.2
## 10        10  52.6
## # ℹ 990 more rows
#Under assumptions of frequentist hypothesis testing, reject the null.
#Step 4 - Visualisation 2
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)

null_distribution
## Response: climateatt (factor)
## Explanatory: lrscale (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  51.1
##  2         2  64.7
##  3         3  66.0
##  4         4 103. 
##  5         5  75.0
##  6         6  52.3
##  7         7  84.1
##  8         8  55.8
##  9         9  92.2
## 10        10  52.6
## # ℹ 990 more rows
#Linear Modelling
models <- list(
"Model 1" <- lm(climateatt ~ lrscale, data = uk_datan),
"Model 2"<- lm(climateatt ~ lrscale + gndr, data = uk_datan),
"Model 3" <- lm(climateatt ~ lrscale + gndr + lrscale * gndr, data = uk_datan),
"Model 4" <- lm(climateatt ~ gndr, data = uk_datan)
)
modelsummary(models)
 (1)   (2)   (3)   (4)
(Intercept) 1.898 1.894 1.893 1.873
(0.010) (0.013) (0.014) (0.011)
lrscaleCenter Left −0.139 −0.139 −0.129
(0.024) (0.024) (0.032)
lrscaleCenter Right 0.044 0.043 0.048
(0.024) (0.024) (0.036)
lrscaleFar Left −0.132 −0.133 −0.221
(0.041) (0.041) (0.057)
lrscaleFar Right 0.001 0.000 0.105
(0.048) (0.048) (0.072)
gndrMale 0.011 0.014 0.014
(0.017) (0.021) (0.017)
lrscaleCenter Left × gndrMale −0.023
(0.049)
lrscaleCenter Right × gndrMale −0.010
(0.049)
lrscaleFar Left × gndrMale 0.181
(0.082)
lrscaleFar Right × gndrMale −0.187
(0.096)
Num.Obs. 1663 1663 1663 1663
R2 0.029 0.030 0.035 0.000
R2 Adj. 0.027 0.027 0.030 0.000
AIC 1119.7 1121.3 1119.8 1162.5
BIC 1152.2 1159.2 1179.4 1178.7
Log.Lik. −553.871 −553.650 −548.906 −578.250
RMSE 0.34 0.34 0.34 0.34
#Linear Modelling with stars (indicating statistical significance)
modelsummary(
  list(`Model 1`, `Model 2`, `Model 3`, `Model 4`),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
              
  statistic = NULL)
 (1)   (2)   (3)   (4)
(Intercept) 1.9 (0.0)*** 1.9 (0.0)*** 1.9 (0.0)*** 1.9 (0.0)***
lrscaleCenter Left −0.1 (0.0)*** −0.1 (0.0)*** −0.1 (0.0)***
lrscaleCenter Right 0.0 (0.0)+ 0.0 (0.0)+ 0.0 (0.0)
lrscaleFar Left −0.1 (0.0)** −0.1 (0.0)** −0.2 (0.1)***
lrscaleFar Right 0.0 (0.0) 0.0 (0.0) 0.1 (0.1)
gndrMale 0.0 (0.0) 0.0 (0.0) 0.0 (0.0)
lrscaleCenter Left × gndrMale 0.0 (0.0)
lrscaleCenter Right × gndrMale 0.0 (0.0)
lrscaleFar Left × gndrMale 0.2 (0.1)*
lrscaleFar Right × gndrMale −0.2 (0.1)+
Num.Obs. 1663 1663 1663 1663
R2 0.029 0.030 0.035 0.000
R2 Adj. 0.027 0.027 0.030 0.000
AIC 1119.7 1121.3 1119.8 1162.5
BIC 1152.2 1159.2 1179.4 1178.7
Log.Lik. −553.871 −553.650 −548.906 −578.250
RMSE 0.34 0.34 0.34 0.34
#Interaction Plot - Model 3
interaction_plot <- effect("lrscale * gndr", `Model 3`, na.rm=TRUE)

plot(interaction_plot,
     main="Interaction effect",
     xlab="Political Ideology",
     ylab="Climate Change Mitigation Opposition Scale")

interaction_plot
## 
##  lrscale*gndr effect
##               gndr
## lrscale          Female     Male
##   Center       1.892508 1.906394
##   Center Left  1.763353 1.754049
##   Center Right 1.940351 1.944203
##   Far Left     1.671408 1.866165
##   Far Right    1.997712 1.824561
# Checks - Model 1
par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row

# plot diagnostics plots
plot(`Model 1`, pch = 19, col = scales::alpha("grey", .8), cex = .5)

#Checks - Model 2
par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row

# plot diagnostics plots
plot(`Model 2`, pch = 19, col = scales::alpha("grey", .8), cex = .5)

#Checks - Model 3
par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row

# plot diagnostics plots
plot(`Model 3`, pch = 19, col = scales::alpha("grey", .8), cex = .5)

#Checks - Model 4
par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row

# plot diagnostics plots
plot(`Model 4`, pch = 19, col = scales::alpha("grey", .8), cex = .5)

#Robust standard Errors
modelsummary(models, vcov = "robust")
 (1)   (2)   (3)   (4)
(Intercept) 1.898 1.894 1.893 1.873
(0.010) (0.012) (0.013) (0.011)
lrscaleCenter Left −0.139 −0.139 −0.129
(0.025) (0.025) (0.033)
lrscaleCenter Right 0.044 0.043 0.048
(0.024) (0.024) (0.034)
lrscaleFar Left −0.132 −0.133 −0.221
(0.048) (0.048) (0.061)
lrscaleFar Right 0.001 0.000 0.105
(0.060) (0.060) (0.081)
gndrMale 0.011 0.014 0.014
(0.017) (0.020) (0.017)
lrscaleCenter Left × gndrMale −0.023
(0.050)
lrscaleCenter Right × gndrMale −0.010
(0.048)
lrscaleFar Left × gndrMale 0.181
(0.096)
lrscaleFar Right × gndrMale −0.187
(0.119)
Num.Obs. 1663 1663 1663 1663
R2 0.029 0.030 0.035 0.000
R2 Adj. 0.027 0.027 0.030 0.000
AIC 1119.7 1121.3 1119.8 1162.5
BIC 1152.2 1159.2 1179.4 1178.7
Log.Lik. −553.871 −553.650 −548.906 −578.250
RMSE 0.34 0.34 0.34 0.34
Std.Errors HC3 HC3 HC3 HC3
# WALD TEST
b <- coef(`Model 1`)

# Extract variance-covariance matrix
Sigma <- vcov(`Model 1`)

# You want to maximize here the Chi-square. Terms = the coefficient you want to check. print b to see sequence of coefficients calculated above

wald_test_polIDRight <- wald.test(Sigma = Sigma, b = b, Terms = 5)

print(wald_test_polIDRight)
## Wald test:
## ----------
## 
## Chi-squared test:
## X2 = 8e-04, df = 1, P(> X2) = 0.98
wald_test_gndr<- wald.test(Sigma = Sigma, b = b, Terms = 2)

print(wald_test_gndr)
## Wald test:
## ----------
## 
## Chi-squared test:
## X2 = 33.0, df = 1, P(> X2) = 9.3e-09
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
#Regression Equation for Model 1
equatiomatic::extract_eq(`Model 1`, use_coefs = TRUE)

\[ \operatorname{\widehat{climateatt}} = 1.9 - 0.14(\operatorname{lrscale}_{\operatorname{Center\ Left}}) + 0.04(\operatorname{lrscale}_{\operatorname{Center\ Right}}) - 0.13(\operatorname{lrscale}_{\operatorname{Far\ Left}}) + 0(\operatorname{lrscale}_{\operatorname{Far\ Right}}) \]