# 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"
ess <- read_fst("All-ESS-Data.fst")
italy_data <- read.fst("italy_data.fst")
france_data <- read.fst("france_data.fst")
spain_data <- read.fst("spain_data.fst")
norway_data <- read.fst("norway_data.fst")
sweden_data <- read.fst("sweden_data.fst")
hungary_data <- read.fst("hungary_data.fst")

Task 1

Provide code and answer.

Prompt: in the tutorial, we calculated the average trust in others for France and visualized it. Using instead the variable ‘Trust in Parliament’ (trstplt) and the country of Spain (country file provided on course website), visualize the average trust by survey year. You can truncate the y-axis if you wish. Provide appropriate titles and labels given the changes. What are your main takeaways based on the visual (e.g., signs of increase, decrease, or stall)?

spain_data <- spain_data %>%
  mutate(
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt)  # set values 77, 88, and 99 to NA.
  )
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
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
trustplt_by_year <- spain_data %>%
  group_by(year) %>%
  summarize(mean_trustplt = mean(trstplt, na.rm = TRUE))
trustplt_by_year
## # A tibble: 10 × 2
##     year mean_trustplt
##    <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
ggplot(trustplt_by_year, aes(x = year, y = mean_trustplt)) +
  geom_line(color = "blue", size = 1, linetype = "longdash") +
  geom_point(color = "red", size = 3) +  # Points to highlight each year's value
  labs(title = "Trust in Parliament in Spain (2002-2020)", 
       x = "Survey Year", 
       y = "Average Trust in Parliament (0-10 scale)") +
  ylim(0, 5) +  # Adjust the y-axis limits as needed
  theme_minimal() +
  theme(legend.position = "none")
## 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.

Key Takeaways: -overall, the line graph depcits that there is a declinign trend in Trust in Parliment in Spain from 2002 to 2020, specially in the year 2012, the peak of trust is seen in 2004 where we see an in incline. there is some stability between 2002-2006 and 2014-2018 indicating that change doesnt occur instantly. To add on , there are many implciations thta can occur leading to incline or decline such as political/economic decisons or even pandemics such as covid-19 which began towards the end of 2019 which can also be a factor as to why there is decrease intrust as it was a difficult period of time.

Task 2

Provide answer only.

Prompt and question: Based on the figure we produced above called task2_plot, tell us: what are your main takeaways regarding France relative to Italy and Norway? Make sure to be concrete and highlight at least two important comparative trends visualized in the graph.

#answer: the code: task2_plot represents the amount of individuals that say yes to feeling close to a political party by cohort. the graph compares three countries; France, italy and Norway. after analayzing we can notcie a few significant comparative trends visualized in the graph. firstly, there is a genrational shidt in france menaning that younger generations are showing low reports for feeling close to a party compared to the older genrations which leads to the decline as years go on due to the decreased party association amongst the younger generations specifically from 1980’s. Secondly, oposed to France, there is a more general stability amongst Norway and Italy. this indicates that as cohorts improve and more along with time individuals staying close with parties does not change significantly. Lastly, to add on it is also important to consider the national and politcal perspectives of each country, which helps understand why France shows a decline as each country has its own generational shifts. therefore, france displays a more distincitve result compared to Norway and Italy.

Task 3

Provide code and answer.

Question: What is the marginal percentage of Italian men who feel close to a particular political party?

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 %in% 0:3 ~ "No",       # Left-wing (0 to 3)
      clsprty %in% 7:10 ~ "Yes",     # Right-wing (7 to 10)
      TRUE ~ NA_character_  # Moderate (4, 5, 6) and special codes (77, 88, 99) set to NA 
    )    
  ) 
clsprty_percentages <- italy_data %>%  # Begin with the dataset 'italy_data'
  filter(!is.na(clsprty), !is.na(gndr)) %>%  
  group_by(gndr, clsprty) %>%  # Group the data by 'gender' and 'clsprty' categories
  summarise(count = n(), .groups = 'drop') %>%  
  mutate(percentage = count / sum(count) * 100)  

clsprty_percentages 
## # A tibble: 4 × 4
##   gndr   clsprty count percentage
##   <chr>  <chr>   <int>      <dbl>
## 1 Female No       4914      48.3 
## 2 Female Yes       415       4.08
## 3 Male   No       4529      44.6 
## 4 Male   Yes       307       3.02

therefore, the marginal percentage for italian men who feel close to a particular politcal party is %3.

Task 4

Provide code and output only.

Prompt: In the tutorial, we calculated then visualized the percentage distribution for left vs. right by gender for France. Your task is to replicate the second version of the visualization but for the country of Sweden instead.

#percent
sweden_data <- sweden_data %>%
  mutate(
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      TRUE ~ NA_character_  
    ),
    lrscale = case_when(
      lrscale %in% 0:3 ~ "Left",       
      lrscale %in% 7:10 ~ "Right",     
      TRUE ~ NA_character_  
    )    
  ) 
#calculate
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
#visualize
lrscale_plot <- ggplot(lrscale_percentages, aes(x = lrscale, y = percentage, fill = lrscale)) +
  geom_bar(stat = "identity", position = position_dodge()) +  
  facet_wrap(~ gndr, scales = "fixed") +  
  scale_fill_brewer(palette = "Set1") +  
  labs(
    title = "Political Orientation (Left vs. Right) by Gender in Sweden",
    x = "Political Orientation",
    y = "Percentage of Respondents",
    fill = "Orientation"
  ) +
  theme_minimal() + 
  theme(legend.position = "bottom")  

lrscale_plot

Task 5

Provide code and answer: In Hungary, what is the conditional probability of NOT feeling close to any particular party given that the person lives in a rural area?

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))
hungary_data <- hungary_data %>%
  filter(!is.na(clsprty)) %>%
  mutate(
    clsprty = case_when(
      clsprty == 1 ~ "Yes",       
      clsprty == 2 ~ "No"
      
    )
  ) %>%
  filter(!is.na(clsprty))
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
##   <chr>   <chr> <int> <dbl>
## 1 No      Rural  6275 0.554
## 2 No      Urban  2395 0.512
## 3 Yes     Rural  5055 0.446
## 4 Yes     Urban  2283 0.488

Therefore, the conditional probability of NOT feeling close to any particular party given that the person lives in a rural area is %55.4.