# List of packages
packages <- c("tidyverse", "fst", "modelsummary", "viridis") # 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.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ 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
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "fst"       "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"    
##  [7] "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"    
## [13] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "modelsummary" "fst"          "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [16] "utils"        "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "viridis"      "viridisLite"  "modelsummary" "fst"          "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"

Task 1

##Gathering Spain data
spain_data <- read.fst("spain_data.fst")
##Sorting the data surrounding trust in parliament
spain_data <- spain_data %>%
  mutate(
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt), 
  )
##Puting data in a table
table(spain_data$trstplt)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
## 5165 1830 2329 2441 2085 2890 1154  639  355   80   71
##Creating a year variable 
spain_data$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  spain_data$year[spain_data$essround == i] <- replacements[i]
}
table(spain_data$year)
## 
## 2002 2004 2006 2008 2010 2012 2014 2016 2018 2020 
## 1729 1663 1876 2576 1885 1889 1925 1958 1668 2283
##Calculating the average by the year to be able to visualize
trust_by_year <- spain_data %>%
  group_by(year) %>%
  summarize(mean_trust = mean(trstplt, na.rm = TRUE))
trust_by_year
## # A tibble: 10 × 2
##     year mean_trust
##    <dbl>      <dbl>
##  1  2002       3.41
##  2  2004       3.66
##  3  2006       3.49
##  4  2008       3.32
##  5  2010       2.72
##  6  2012       1.91
##  7  2014       2.23
##  8  2016       2.40
##  9  2018       2.55
## 10  2020       1.94
##Vizualizing data
ggplot(trust_by_year, aes(x = year, y = mean_trust)) +
  geom_line(color = "blue", linewidth = 1) +  
  geom_point(color = "red", linewidth = 3) +  
  labs(title = "Trust in Parliament in Spain (2002-2020)", 
       x = "Survey Year", 
       y = "Average Trust (0-10 scale)") +
  ylim(0, 10) +  # Setting the y-axis limits from 0 to 10
  theme_minimal()
## Warning in geom_point(color = "red", linewidth = 3): Ignoring unknown
## parameters: `linewidth`

##This shows that there was a visible decrease from 2010 to 2012 with the average trust individuals from Spain have in parliament This decrease is about 0.8% of a decrease and is the most visible decrease visible in this data.



#Task 2

##Both Norway and France have decreases in the population of people sayig yes to feeling close to a  party by cohort.  Both decreases were major in the 1940s.  Italy, however, has more of a dramatic decrease in between the 1950s and the 1960s.  Norway is also visibly the highest which means Norway has the most proportions of people saying yes to feeling close to a party compared to the citizens of Italy and France.  This means the people of Italy and France do not feel as close as the people of Norway do.  All of Norways proportions are above 0.50. Proportions in Italy are all under 0.40, making it the most visibly smaller in terms of proportions.  France remains in the middle in a more mutual manner as it is in between 0.40 and 0.75.

Task 3

##Gathering data for Italy
italy_data <- read.fst ("italy_data.fst")
##Sorting by gender
italy_data <- italy_data %>%
  mutate(
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      TRUE ~ NA_character_  # Set anything that is not 1 or 2 to NA
    ),
    clsprty = case_when(
      clsprty == 1 ~ "YES",
      clsprty == 2 ~ "NO",
      TRUE ~ NA_character_  # Moderate (4, 5, 6) and special codes (77, 88, 99) set to NA 
    )    
  )
##Sorting class party data
clsprty_percentages <- italy_data %>%
  filter(!is.na(clsprty), !is.na(gndr)) %>%
  group_by(gndr, clsprty) %>%
  summarise(count = n (), .groups = 'drop') %>%
  mutate(percentages = count / sum(count) * 100)
clsprty_percentages
## # A tibble: 4 × 4
##   gndr   clsprty count percentages
##   <chr>  <chr>   <int>       <dbl>
## 1 Female NO       3228        34.2
## 2 Female YES      1686        17.9
## 3 Male   NO       2593        27.5
## 4 Male   YES      1936        20.5

##The Marginal percentage of Italian men who feel close to a particular political party is 20.5%.

Task 4

sweden_data <- read.fst ("sweden_data.fst")
##Calculating the percentage

sweden_data <- sweden_data %>%
  mutate(
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      TRUE ~ NA_character_  # Set anything that is not 1 or 2 to NA
    ),
    lrscale = case_when(
      lrscale %in% 0:3 ~ "Left",       # Left-wing (0 to 3)
      lrscale %in% 7:10 ~ "Right",     # Right-wing (7 to 10)
      TRUE ~ NA_character_  # Moderate (4, 5, 6) and special codes (77, 88, 99) set to NA 
    )    
  ) 
##Calculations
lrscale_percentages <- sweden_data %>% 
  filter(!is.na(lrscale), !is.na(gndr)) %>%  
  group_by(gndr, lrscale) %>%  #
  summarise(count = n(), .groups = 'drop') %>%  
  mutate(percentage = count / sum(count) * 100)  

lrscale_percentages 
## # A tibble: 4 × 4
##   gndr   lrscale count percentage
##   <chr>  <chr>   <int>      <dbl>
## 1 Female Left     2296       23.0
## 2 Female Right    2530       25.3
## 3 Male   Left     2062       20.6
## 4 Male   Right    3107       31.1
lrscale_plot_v2 <- ggplot(lrscale_percentages, 
            aes(x = percentage,  
                y = reorder(gndr, -percentage), 
                fill = gndr)) +  

  # Creating a horizontal bar chart
  geom_col() + 
  coord_flip() +  

  # Removing fill color legend
  guides(fill = "none") +  

  # Spliting the plot based on Political Orientation
  facet_wrap(~ lrscale, nrow = 1) +  
  
  # Labels and titles for the plot
  labs(x = "Percentage of Respondents",  
       y = NULL,
       title = "Political Orientation by Gender", 
       subtitle = "Comparing the percentage distribution of left vs. right for Sweden (2002-2020)") + 
  
  # Adjusting the visual properties of the plot
  theme(plot.title = element_text(size = 16, face = "bold"),  
        plot.subtitle = element_text(size = 12),  
        axis.title.y = element_blank(),
        legend.position = "bottom") 

# Displaying the ggplot object
lrscale_plot_v2

Task 5

hungary_data <- read.fst ("hungary_data.fst")
##Calculating and sorting based on year
hungary_data <- hungary_data %>%
  mutate(
    clsprty = ifelse(clsprty == 2, 0, ifelse(clsprty %in% c(7, 8, 9), NA, clsprty))
  ) %>%
  mutate(
    yrbrn = ifelse(yrbrn %in% c(7777, 8888, 9999), NA, yrbrn)
  )
##Sorting and grouping based on year
clsprty_proportions <- hungary_data %>%
  filter(!is.na(yrbrn) & yrbrn >= 1920 & !is.na(clsprty)) %>%  
  group_by(yrbrn, clsprty) %>%
  tally() %>%
  mutate(proportion = n / sum(n)) %>%
  
  ungroup()
##Sorting urban vs rural data in Hungary
hungary_data <- hungary_data %>%
  mutate(
    geo = recode(as.character(domicil), 
                 '1' = "Urban", 
                 '2' = "Urban",
                 '3' = "Rural", 
                 '4' = "Rural", 
                 '5' = "Rural",
                 '7' = NA_character_,
                 '8' = NA_character_,
                 '9' = NA_character_)
  ) %>%
  filter(!is.na(clsprty), !is.na(geo))  
cond <- hungary_data %>%
  count(clsprty, geo) %>%
  group_by(geo) %>%
  mutate(prob = n / sum(n))

cond
## # A tibble: 4 × 4
## # Groups:   geo [2]
##   clsprty geo       n  prob
##     <dbl> <chr> <int> <dbl>
## 1       0 Rural  6275 0.554
## 2       0 Urban  2395 0.512
## 3       1 Rural  5055 0.446
## 4       1 Urban  2283 0.488

##The conditional probability of not feeling close to any particular party in a rural area is 0.5538394