setwd("C:/Users/Talia/Desktop/OneDrive - University of Toronto/FALL 2023/SOC202 Quan/Homework_5_Project")

# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr")

# 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: 'kableExtra'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## [[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] "kableExtra"   "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] "rmarkdown"    "kableExtra"   "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"    "kableExtra"   "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"        
## 
## [[11]]
##  [1] "ggridges"     "rmarkdown"    "kableExtra"   "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] "questionr"    "ggridges"     "rmarkdown"    "kableExtra"   "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"
ess <- read_fst("All-ESS-Data.fst")

TASK 1

#Do a data summary table of three variables of interest. Discuss briefly what you note (i.e., add text in your markdown after the Task 1 code).

#Variable 1: badge - Worn or displayed campaign badge/sticker last 12 months https://ess-search.nsd.no/en/variable/cd2e3204-99c6-4ede-89a8-a92ac54ff774
#Variable 2: netusoft - Internet use, how often https://ess-search.nsd.no/en/variable/49fcf969-aeab-42f5-9b11-807cb2306df0
#Variable 3:polintr - How interested in politics https://ess-search.nsd.no/en/variable/f08a0d6a-a5bf-42d4-9565-80fe44673914
#year subset
table(ess$essround)
## 
##     1     2     3     4     5     6     7     8     9    10 
## 42359 47537 43000 56752 52458 54673 40185 44387 49519 59685
ess$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  ess$year[ess$essround == i] <- replacements[i]
}
# getting to know variables
table(ess$badge)
## 
##      1      2      7      8      9 
##  36109 451906    382   1272    886
table(ess$netusoft)
## 
##     1     2     3     4     5     7     8     9 
## 23872  9013  8739 14124 97494    49   101   199
table(ess$polintr)
## 
##      1      2      3      4      7      8      9 
##  52651 171323 170951  93989    251    955    435
#cleaning data
sweden_data <- ess %>%
  filter(cntry == "SE") %>% 
  mutate(
    badge = ifelse(badge == 2, 0, ifelse(badge %in% c(7, 8, 9), NA, badge)), 
    netusoft = ifelse(netusoft %in% c(7, 8, 9), NA, netusoft),
    polintr = ifelse(polintr %in% c(7, 8, 9), NA, polintr),
  )
#checking data
table(sweden_data$badge)
## 
##     0     1 
## 15399  2761
table(sweden_data$netusoft)
## 
##    1    2    3    4    5 
##  289  158  155  355 4402
table(sweden_data$polintr)
## 
##    1    2    3    4 
## 2727 8530 5480 1458
#datasummary
datasummary_skim(sweden_data %>% select(badge, polintr, netusoft))
Unique (#) Missing (%) Mean SD Min Median Max
badge 3 0 0.2 0.4 0.0 0.0 1.0
polintr 5 0 2.3 0.8 1.0 2.0 4.0
netusoft 6 71 4.6 1.1 1.0 5.0 5.0
#findings: badge is right skewed, with badge having a small outlier. polintr is normal, and netusoft is left skewed/.
#interestingly, netusoft has a high missing percentage. going into the data, I could not find a definite reason why. However, I can guess this may be because it is new variable, first being introduced in 2016.
#polintr has the biggest range, from 2-4, while netusoft has the smallest 5-5.

TASK 2

#Choose one of the three variables you just summarized in the table. This will be your current main outcome of interest.

# Produce a visual that showcases the mean (average) for your outcome of interest by survey year (can be, e.g., point + line plot or ridge plot, depending on your variable). Discuss briefly what you note (i.e., add text in your markdown after the Task 2 code).
sweden_data %>%
  ggplot(aes(x = polintr, y = as.factor(year), fill = as.factor(year))) +
  geom_density_ridges() + 
  labs(title = "How interested in politics - Sweden", 
       x = "Very Interested - Not at all Interested (1-4)", y = "Survey Year",
       fill = "Survey Year") +
  theme_minimal()
## Picking joint bandwidth of 0.15
## Warning: Removed 21 rows containing non-finite values
## (`stat_density_ridges()`).

# The graph has stayed consistent with its peaks, with 2018 being the year with the least amount of people not being interested in politics, and more being very interested.The biggest group in every year has been "Quite Interested".

TASK 3

# Provide a comparison visual of your outcome of interest with two other countries. You can choose the geom() you prefer. Discuss briefly what you note (i.e., add text in your markdown after the Task 3 code).
t3countries <- ess %>%
  filter(cntry %in% c("SE", "HU", "GB")) %>%
  mutate(polintr = ifelse(polintr %in% c(7, 8, 9), NA, polintr))


t3plot <- ggplot(t3countries, aes(x = reorder(cntry, -polintr, FUN=median), y = polintr, fill = cntry)) +
  geom_boxplot() +
  theme_minimal() + 
  theme(legend.position = "none") + 
  labs(title = "Boxplot Comparison for How Interested in Politics (Sweden, Hungary, Great Britian)", 
       x = "Country", 
       y = "Very Interested - Not at all Interested (1-4)")

t3plot
## Warning: Removed 90 rows containing non-finite values (`stat_boxplot()`).

# Great Britian and Sweden are consistent with eachother, having the same distribution, IQR, and median and no outliers. For every country, the minimum and maximum is the same. However, Hungary's median is higher than Great Britian's and Sweden's, indicating that more people are not interested in politics. Its IQR also adds to this finding, with Q3 ending on 4 - Not at All Interested. 

TASK 4

# Produce a cross-tab between your outcome of interest and a socio-demographic variable (use datasummary_crosstab). Then, calculate column percentages using cprop(), making sure to pick a second socio-demographic variable. Discuss briefly what you note (i.e., add text in your markdown after the Task 4 code).
#religion: https://ess-search.nsd.no/variable/query/rlgblg/1
sweden_data <- sweden_data %>%
  mutate(religion = case_when(
    rlgblg == 2 ~ "No",
    rlgblg == 1 ~ "Yes",
    rlgblg %in% c(7, 8, 9) ~ NA_character_,
    TRUE ~ as.character(rlgblg)
  ))

table(sweden_data$religion)
## 
##    No   Yes 
## 10721  5167
table(sweden_data$rlgblg)
## 
##     1     2     7     8     9 
##  5167 10721     8    30     3
# ever had a paid job? https://ess-search.nsd.no/en/variable/bcc09f4e-ad04-4a32-91f7-69268e981978
sweden_data <- sweden_data %>%
  mutate(paidjob = case_when(
    pdjobev == 2 ~ "No",
    pdjobev == 1 ~ "Yes",
    pdjobev %in% c(6, 7, 8, 9) ~ NA_character_,
    TRUE ~ as.character(pdjobev)
  ))

table(sweden_data$paidjob)
## 
##   No  Yes 
##  691 6283
table(sweden_data$pdjobev)
## 
##     1     2     6     7     8     9 
##  6283   691 11183    10     6    43
#crosstabs
polintrreligion <- datasummary_crosstab(polintr ~ religion, data = sweden_data)
polintrpaidjob <- datasummary_crosstab(polintr ~ paidjob, data = sweden_data)
polintrreligion
polintr No Yes All
1 N 1519 875 2727
% row 55.7 32.1 100.0
2 N 4865 2590 8530
% row 57.0 30.4 100.0
3 N 3368 1366 5480
% row 61.5 24.9 100.0
4 N 964 331 1458
% row 66.1 22.7 100.0
All N 10721 5167 18216
% row 58.9 28.4 100.0
polintrpaidjob
polintr No Yes All
1 N 63 961 2727
% row 2.3 35.2 100.0
2 N 237 2985 8530
% row 2.8 35.0 100.0
3 N 236 1788 5480
% row 4.3 32.6 100.0
4 N 154 537 1458
% row 10.6 36.8 100.0
All N 691 6283 18216
% row 3.8 34.5 100.0
#column percentages
table(sweden_data$polintr, sweden_data$religion) %>%
  cprop()
##        
##         No    Yes   All  
##   1      14.2  17.0  15.1
##   2      45.4  50.2  47.0
##   3      31.4  26.5  29.8
##   4       9.0   6.4   8.2
##   Total 100.0 100.0 100.0
table(sweden_data$polintr, sweden_data$paidjob) %>%
  cprop()
##        
##         No    Yes   All  
##   1       9.1  15.3  14.7
##   2      34.3  47.6  46.3
##   3      34.2  28.5  29.1
##   4      22.3   8.6   9.9
##   Total 100.0 100.0 100.0
# People are likeler to be more interested in a politics if they are religious. They are less likely to be interested in politics if they have never had a paid job. For all groupings, 2, "Quite Interested" in politics hold the greatest group.

TASK 5

#Choose one of the two socio-demographic variables you just worked with. Visualize the conditional probability (or column percentages) of your outcome given your selected socio-dem variable. Discuss briefly what you note (i.e., add text in your markdown after the Task 5 code).
df <- sweden_data %>%
  filter(!is.na(paidjob) & !is.na(polintr))

df <- df %>%
  mutate(polintr = case_when(
    polintr == 1 ~ "Very Interested",
    polintr == 2 ~ "Quite Interested",
    polintr == 3 ~ "Hardly Interested",
    polintr == 4 ~ "Not At All Interested",
    TRUE ~ as.character(polintr)  # or "Other", or NA_character_, depending on your needs
  ))

table(df$polintr)
## 
##     Hardly Interested Not At All Interested      Quite Interested 
##                  2024                   691                  3222 
##       Very Interested 
##                  1024
table(df$polintr, df$paidjob) %>%
  cprop() %>%
  as.data.frame() %>%
  filter(Var1 != "Total",
         Var2 != "All") %>%
  ggplot(aes(x=Var1, y=Freq, fill=Var2)) +
  geom_col(position = "dodge") +
  labs(title="How Interested in Politics in Sweden",
       y = "Conditional Percentage",
       x = "How Interested",
       fill = "Ever Had a Paid Job vs. Not")

# People who have not held a paid job are overall less interested in politics. The groups for No and Yes are switched in the X-axis for Not At All Interested/Very Interested, with Very Interested beng smallest Group, and Quite Interested being the highest. This chart differs from the Joy Plot (unsure of the actual name), as the Hardly Interested demographic has a much higher conditional percentage here, than in the Joy Plot, although Quite Interested remains the largest demographic