# Setting up environment
packages <- c("tidyverse", "infer", "fst", "modelsummary", "broom")
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.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"     
## 
## [[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] "broom"        "modelsummary" "fst"          "infer"        "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"
ess <- read_fst("All-ESS-Data.fst")
# Task 1
# Extract the coefficients and intercept using trust in the European Parliament (as the outcome) and worked in a political party (wrkprty, as the explanatory), for the country of Belgium. Write the regression equation and interpret.
belgium_data <- ess |>
  filter(cntry == "BE") |>
  mutate(trstep = ifelse(trstep %in% c(77, 88, 99), NA, trstep),
         )

unique(belgium_data$trstep)
##  [1]  0  7  8  5  6 NA  4  9  3  1 10  2
belgium_data <- belgium_data |> filter(!is.na(trstep))

belgium_data <- belgium_data |>
  mutate(wrkprty = case_when(
    wrkprty == 1 ~ "Yes",
    wrkprty == 2 ~ "No",
    wrkprty %in% c(7, 8, 9) ~ NA_character_,
    TRUE ~ as.character(wrkprty)
  ))

table(belgium_data$wrkprty)
## 
##    No   Yes 
## 14871   727
model1 <- lm(trstep ~ wrkprty, data = belgium_data)

coefficients <- coef(model1)
print(coefficients)
## (Intercept)  wrkprtyYes 
##   4.9405554   0.4308338
equatiomatic::extract_eq(model1, use_coefs = TRUE)

\[ \operatorname{\widehat{trstep}} = 4.94 + 0.43(\operatorname{wrkprty}_{\operatorname{Yes}}) \]

# trstep(hat) = 4.94 + 0.43 (wrkprtyYES) + error term
# Interpretation: 
# (Intercept is 4.940554):
# The intercept represents the predicted value of the outcome variable (in this case, Trust in European Parliament 0-9).
# Put differently, when looking at the category that’s NOT in the working party (thus, holding a “wrkprtyNo”), the expected value of trstep is approximately 4.940554.
# wrkprtyYes 0.4308338:
# This coefficient represents the difference in the predicted value of trust in the European Parliament between the (“wrkprtyNo”) category and the reference category (“wrkprtyYes”) for the wrkprty variable.
# Specifically, being in the working party is associated with an increase of approximately 0.43 in the predicted value of trust in politicians, compared to not being in the working party.
# In summary: If a person is in the working party (assuming that’s the reference category), their predicted average trust in the European Parliament is 4.94. If a person is in the working party, their predicted average trust in European Parliament is 5.37 (given 4.94 + 0.43). Additionally, the regression equation shows this linear relationship between the change in trust in the European Parliament when the variable of working in a political party is taken into account. 
# Task 2
# Produce a model summary output using either tidy() or summary() (your choice). Use stfdem (satisfaction with democracy) as the outcome and born in country as a predictor (which we recoded/renamed as ‘native’ in the tutorial), for the country of Bulgaria. What is the expected average satisfaction with democracy for respondents that were not born in Bulgaria?
bulgaria_data <- ess |>
  filter(cntry == "BG") |>
  mutate(
    stfdem = ifelse(stfdem %in% c(77, 88, 99), NA, stfdem),
    native = recode(brncntr,
                             `1` = "Yes",
                             `2` = "No",
                             `7` = NA_character_,
                             `8` = NA_character_,
                             `9` = NA_character_)
  )

table(bulgaria_data$stfdem)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
## 2247 1589 1778 1969 1597 1742  640  400  206   86   84
table(bulgaria_data$native)
## 
##    No   Yes 
##   104 13134
model1 <- lm(stfdem ~ native, data = bulgaria_data)

coefficients <- coef(model1)
print(coefficients)
## (Intercept)   nativeYes 
##   2.8041237   0.1189909
tidy(model1)
## # A tibble: 2 × 5
##   term        estimate std.error statistic  p.value
##   <chr>          <dbl>     <dbl>     <dbl>    <dbl>
## 1 (Intercept)    2.80      0.226    12.4   5.30e-35
## 2 nativeYes      0.119     0.227     0.523 6.01e- 1
# The expected average satisfaction with democracy for respondents that were not born in Bulgaria is 2.804, aka the intercept. 
# Task 3
# Based on your own outcome and country of interest, as well as one of the predictors recoded in the tutorial, produce an equatiomatic regression equation. Interpret the regression equation.
UK_data <- ess |>
  filter(cntry == "GB") |>
  mutate(
     ppltrst = ifelse(ppltrst %in% c(77, 88, 99), NA, ppltrst),
     protest = case_when(
       pbldmn == 1 ~ "Yes",
       pbldmn == 2 ~ "No",
       pbldmn %in% c(7, 8, 9) ~ NA_character_,
    TRUE ~ as.character(pbldmn))
  )

table(UK_data$ppltrst)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
##  802  508 1042 1946 2209 4639 2648 3831 2524  474  307
table(UK_data$protest)
## 
##    No   Yes 
## 18990   829
model1 <- lm(ppltrst ~ protest, data = UK_data)

coefficients <- coef(model1)
print(coefficients)
## (Intercept)  protestYes 
##   5.2618633   0.4398275
equatiomatic::extract_eq(model1, use_coefs = TRUE)

\[ \operatorname{\widehat{ppltrst}} = 5.26 + 0.44(\operatorname{protest}_{\operatorname{Yes}}) \]

# ppltrst (hat) = 5.26 + 0.44(ProtestYES) + error term
# Interpretation 
# (Intercept is 5.26):
# The intercept represents the predicted value of the outcome variable (in this case, ppltrst - Most people can be trusted or you can't be too careful) 
# Put differently, when looking at the category that’s NOT ProtestYes (thus, holding a “ProtestNo”), the expected value of  pbldmn is approximately 5.26.
# ProtestYes is 0.44:
# This coefficient represents the difference in the predicted value of ppltrst between the (“ProtestNo”) category and the reference category (“ProtestYes”) for the ppltrst variable.
# Specifically, having participated in a protest in the last year is associated with an increase of approximately 0.44 in the predicted value of ppltrst, compared to not being involved in a protest in the last year.
# In summary: If a person hasn’t participated in a political protest in the last year (assuming that’s the reference category), their predicted average ppltrst is 5.26. If a person has been involved in a protest in the last year, their predicted average trust in ppltrst is 5.66 (given 5.26 + 0.44). Additionally, the regression equation shows this linear relationship between the change in trust in people when the variable of being in a political protest in the past year is taken into account.