# 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.5
## ✔ 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"

##Task1 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 <- read.fst("spain_data.fst")
library(ggplot2)
library(dplyr)
# Set values 77, 88, and 99 to NA in 'trstplt'
spain_data <- spain_data %>%
  mutate(
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt)
  )
# Check the values after modification
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
# Create a 'year' variable from the 'essround' 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]
}
# Calculate the average trust in Parliament by year
trust_by_year <- spain_data %>%
  group_by(year) %>%
  summarize(mean_trust_plt = mean(trstplt, na.rm = TRUE))
# Visualize the trend
ggplot(trust_by_year, aes(x = year, y = mean_trust_plt)) +
  geom_line(color = "blue", size = 1) +  # Line to show the trend
  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") +
  ylim(0, 10) +  # Setting the y-axis limits from 0 to 10
  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.

Answer: A slight decrease is shown over the designated years, althought a noticable dip in average trust in the year 2012

##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: There are a number of outliers within the earlier years, very low proportions for italy and very high for norway. All three countries show a negative correlation in more recent years. In France’s early years shown in this visualization it shows trends very similiar but slightly weaker than that of norway, whereas closest to the the 21st century, it beings to trend towards italies slope whilst remaining just above it.

##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 <- read_fst("italy_data.fst")  
# Recode gndr and lrscale variables
italy_data <- italy_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 percentages
lrscale_percentages <- italy_data %>%
  filter(!is.na(lrscale), !is.na(gndr)) %>%
  group_by(gndr, lrscale) %>%
  summarise(count = n(), .groups = 'drop') %>%
  mutate(percentage = count / sum(count) * 100)

# Print the resulting dataframe
lrscale_percentages
## # A tibble: 4 × 4
##   gndr   lrscale count percentage
##   <chr>  <chr>   <int>      <dbl>
## 1 Female Left      930       23.9
## 2 Female Right     955       24.5
## 3 Male   Left      924       23.7
## 4 Male   Right    1084       27.8

Answer: Male and Right: 27.8% of all Italian respondents are males who lean politically right. Male and Left: 23.7% of all Italian respondents are males who lean politically left.

##Task4 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.

sweden_data <- read_fst("Sweden_data.fst")
# Recode gender and political orientation variables
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 percentages
lrscale_percentages_sweden <- sweden_data %>%
  filter(!is.na(lrscale), !is.na(gndr)) %>%
  group_by(gndr, lrscale) %>%
  summarise(count = n(), .groups = 'drop') %>%
  mutate(percentage = count / sum(count) * 100)
# Create a ggplot object for horizontal bar chart with the specified style
lrscale_plot_sweden <- ggplot(lrscale_percentages_sweden, 
                              aes(x = percentage,  # Use percentage directly
                                  y = reorder(gndr, -percentage),  # Order bars within each gender
                                  fill = gndr)) +  # Fill color based on Gender

  # Create horizontal bar chart
  geom_col() +  # Draws the bars using the provided data
  coord_flip() +  # Flip coordinates to make bars horizontal

  # Remove fill color legend
  guides(fill = "none") +  # Removes legend for the fill aesthetic

  # Split the plot based on Political Orientation
  facet_wrap(~ lrscale, nrow = 1) +  # Separate plots for Left/Right

  # Labels and titles for the plot
  labs(x = "Percentage of Respondents",  # X-axis label
       y = NULL,  # Remove Y-axis label
       title = "Political Orientation by Gender",  # Main title
       subtitle = "Comparing the percentage distribution of left vs. right for Sweden") +  # Subtitle

  # Adjust visual properties of the plot
  theme(plot.title = element_text(size = 16, face = "bold"),  # Format title
        plot.subtitle = element_text(size = 12),  # Format subtitle
        axis.title.y = element_blank(),  # Remove Y-axis title
        legend.position = "bottom")  # Position the legend at the bottom

# Display the ggplot object
lrscale_plot_sweden

##Task5 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 <- read_fst("hungary_data.fst")
hungary_data <- hungary_data %>%
  mutate(
    geo = case_when(
      domicil %in% c(1, 2) ~ "Urban",  # Assuming 1 and 2 represent urban areas
      domicil %in% c(3, 4, 5) ~ "Rural",  # Assuming 3, 4, and 5 represent rural areas
      TRUE ~ NA_character_
    )
  ) %>%
  filter(!is.na(geo), !is.na(lrscale), !lrscale %in% c(77, 88, 99))  # Removing rows with NA in geo, lrscale, and excluding 77, 88, 99
# Convert lrscale to factor
hungary_data$lrscale <- as.factor(hungary_data$lrscale)
# Calculate conditional probabilities, excluding NAs for Hungary_data
cond_hungary <- hungary_data %>%
  count(lrscale, geo) %>%
  group_by(geo) %>%
  mutate(prob_not_feeling_close = sum(n[lrscale %in% c(0, 1)]) / sum(n))

# Print conditional probabilities for Hungary_data
print(cond_hungary)
## # A tibble: 22 × 4
## # Groups:   geo [2]
##    lrscale geo       n prob_not_feeling_close
##    <fct>   <chr> <int>                  <dbl>
##  1 0       Rural   314                 0.0566
##  2 0       Urban   234                 0.0817
##  3 1       Rural   233                 0.0566
##  4 1       Urban   107                 0.0817
##  5 2       Rural   469                 0.0566
##  6 2       Urban   215                 0.0817
##  7 3       Rural   637                 0.0566
##  8 3       Urban   337                 0.0817
##  9 4       Rural   632                 0.0566
## 10 4       Urban   332                 0.0817
## # ℹ 12 more rows
# Plot conditional probabilities for Hungary_data
plot_hungary <- ggplot(cond_hungary, aes(x = lrscale, y = prob_not_feeling_close, fill = lrscale)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_viridis_d(name = "Political Orientation") + 
  labs(y = "Conditional Probability", 
       x = "Political Orientation",
       title = "Conditional Probability of Not Feeling Close to Any Political Party in Hungary", 
       subtitle = "by Geographical Area: Urban vs. Rural") + 
  facet_wrap(~ geo, nrow = 1) + 
  theme(legend.position = "bottom", 
        legend.title = element_blank(), 
        plot.title = element_text(size = 16, face = "bold"),
        plot.subtitle = element_text(size = 12), 
        axis.text.x = element_text(angle = 45, hjust = 1)) 

# Display the plot for Hungary_data
plot_hungary

Answer:In Hungary, the conditional probability of not feeling close to any particular party given that the person lives in a rural area is 60%.