First things first: setting up your environment

Remember: you always need to do this step first and include all the packages you need

# 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"

Loading Data into R

Let’s load our data. We will first work with France.

france_data <- read.fst("france_data.fst")

Homework 2 (5%): due by next lecture on Jan. 30

Instructions: Start a new R markdown for the homework and call it “Yourlastname_Firstname_Homework_2”.

Copy everything below from Task 1 to Task 5. Keep the task prompt and questions, and provide your code and answer underneath.

Remember: you need all the steps for your code to work, including loading your data – otherwise it will not knit.

To generate a new code box, click on the +C sign above. Underneath your code, provide your answer to the task question.

When you are done, click on “Knit” above, then “Knit to Html”. Wait for everything to compile. If you get an error like “Execution halted”, it means there are issues with your code you must fix. When all issues are fixed, it will prompt a new window. Then click on “Publish” in the top right, and then Rpubs (the first option) and follow the instructions to create your Rpubs account and get your Rpubs link for your document (i.e., html link as I provide for the tutorial).

Note: Make sure to provide both your markdown file and R pubs link. If you do not submit both, you will be penalized 2 pts. out of the 5 pts. total.

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 <- read.fst("spain_data.fst")
spain_data <- spain_data %>%
  mutate(
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
  )
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

This table displays the variable of trust in parliment (trstplt) rated through 0-10 in the country of Spain. It reveals that there is a lack of trust from the people of Spain in their parliment as, 5165 rated having a 0 trust, and only 71 with the highest trust.

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

This table presents the years to applicant, displaying how often people from Spain demonstrate the satisfaction/trust, revealing that there has been a steady increase in the amount of applicants responding to the survey.

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

This chunk displays the average trust Spanish people exhibit, with a stark decrease from 2002 - 2020, starting at 3.41 and dropping to 1.93 percent, however, it can be seen that there was a sudden decrease during the 2012 year, being a 1.91 percent, being the lowest recorded for Spain.

ggplot(trust_by_year, aes(x = year, y = mean_trust)) +
  geom_line(color = "blue", size = 1) +
  geom_point(color = "red", size = 3) + 
  labs(title = "Trust in Parliment in Spain (2002-2020)", 
       x = "Survey Year", 
       y = "Average Trust (0-10 scale)") +
  ylim(0, 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.

## This graph demonstrates the gradual decrease in the trust in parliment in Spain as seen from the geom line being blue and geom point being red. Each geom point represents the data from the previous table of average trust. As can be seen, through visualization, we can see the gradual decrease more clearly, with the sudden drop during the 2012 year, then a slight increase following into the 2017 year, with the high trust average being seen in 2018, then another fall in trust in both 2019-2020.

ggplot(trust_by_year, aes(x = year, y = mean_trust)) +
  geom_line(aes(group = 1), color = "blue", size = 1, linetype = "longdash") +

  labs(title = "Trust in Parliment in Spain (2002-2020)", 
       x = "Survey Year", 
       y = "Average Trust (0-10 scale)") +
  ylim(0, 10) +  
  theme_minimal() + 
  theme(legend.position = "none")

## This graph also demonstrates the gradual decrease in trust by Spanish people, however, it is altered to only visualize the geom line.

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.

One trend that can be visualized is the gradual decrease for Norway, as the proportion of the population that is close to a party based by cohort is more steadily decreaseing compared to Italy and France, with highest attachment to a party being observed at the start of 1920, the a gradual dip around 1940-1945, then a slight increase around 1950, then after that year, the proportion of people feeling close to a party has decreased.

Another trend can be visualized for France, as there was a rapid decrease to the proportion of the population feeling close to a part, where the highest attachment to a party being observered to be around 1935-1940, and after 1940, there has been a rapid decrease to the proportion to cohort ratio.

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")
italy_data <- italy_data %>%
  mutate(
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      TRUE ~ NA_character_
    ),
    clsprty = case_when(
      clsprty == 1 ~ "Yes",    
      clsprty == 2 ~ "No",  
      TRUE ~ NA_character_ 
    )    
  ) 

This chuck of code displays the gender (gndr) and variable close to a particular political party (clsprty).

clsprty_percentages <- italy_data %>%
  filter(!is.na(clsprty), !is.na(gndr)) %>%  
  group_by(gndr, clsprty) %>% 
  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       3228       34.2
## 2 Female Yes      1686       17.9
## 3 Male   No       2593       27.5
## 4 Male   Yes      1936       20.5

This table displays the marginal percentage of Italian men that feel partcularly close to a political party, with only 20.5 percent of Italian male respondent responding with “Yes” to feeling close to a political party, and another 27.4 responding with a “No” to the question. It also demonstrates that Italian women have a stark indifference in not feeling close to a political party, with 34.1 percent of Italian women responding with a “No”, and only 17.8 percent that responded with “Yes”.

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.

sweden_data <- read.fst("sweden_data.fst")
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_ 
    )    
  ) 
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

This table filters the political orientation based by gender. As displayed, Females lean more to a political right, with 25.3 percent responding, and 22.9 responding to a political left.

Male respondent however, are more leaning to a political right with 31 percent responding to this option compared to the 20.6 percent that replied to a political left.

lrscale_plot_v2 <- ggplot(lrscale_percentages, 
            aes(x = percentage,
                y = reorder(gndr, -percentage), 
                fill = gndr)) + 

  geom_col() +  
  coord_flip() +  

  guides(fill = "none") +

  facet_wrap(~ lrscale, nrow = 1) + 

   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)") +
  
  theme(plot.title = element_text(size = 16, face = "bold"),  
        plot.subtitle = element_text(size = 12),
        axis.title.y = element_blank(), 
        legend.position = "bottom") 

lrscale_plot_v2

## This graph is a visualized version of the table above. As displayed, men have a more drastic political orientation to the right.

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 <- read.fst("hungary_data.fst")
hungary_data <- hungary_data %>%
  mutate(    
    clsprty = case_when(
      clsprty == 1 ~ "Yes",    
      clsprty == 2 ~ "No",  
      TRUE ~ NA_character_ 
    ),    
    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))  

This chunk filters the variable clsprty, close to a party, based on geographic location.

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

This table displays the rating of participants feeling close to a party based on geographic location. As presented, rural areas have a higher tendency to respond to a “no” compared to urban areas.

plot <- ggplot(cond, aes(x = clsprty, y = prob, fill = clsprty)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_viridis_d(name = "Political Orientation") + 
  labs(y = "Conditional Probability", 
       x = "Feels Close to a Party",
       title = "Conditional Probability of Political Orientation 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)) 


plot

## This graphy exhibits the visualized version of the table above. As displayed, rural areas have a higher discrepancy in their response, compared to urban areas, where they have similar ratios to an attachment to a Political Orientation.