---
title: "PA 8: United Nations Voting Records"
author: "Add Names Here"
format: html
embed-resources: true
code-tools: true
toc: true
editor: source
execute: 
  error: false
  echo: true
---

```{r}
#| label: setup
#| include: false
library(tidyverse)
library(lubridate) #should already be installed as a part of the tidyverse, we will talk more about this in Week 10
library(scales)  #you may need to install package `scales`
library(janitor) #for a nice feature for summing rows
```


***This task is complex. It requires many different types of abilities. Everyone will be good at some of these abilities but nobody will be good at all of them. In order to produce the best product possible, you will need to use the skills of each member of your group.***

<!-- The partner was born the furthest away from CSUMB will start as the Computer (typing and listening to instructions from the Coder)!  -->

- Starting Computer:  

- Starting Coder:    


## Goals for the Activity  

- Join multiple data tables together by a common variable(s)  
- Create new data sets through the joining of data from various sources  
- Combine `join` functions with other `tidyverse` functions  

**THROUGHOUT THE Activity** be sure to follow the Style Guide by doing the following:  

- load the appropriate packages at the beginning of the Quarto document  
- use proper spacing  
- *add labels* to all code chunks  
- comment at least once in each code chunk to describe why you made your coding decisions  
- add appropriate labels to all graphic axes  


# Data Description
The data this week comes from Harvard's Dataverse by way of Mine Çetinkaya-Rundel, David Robinson, and Nicholas Goguen-Compagnoni.

> Original Data citation: Erik Voeten "Data and Analyses of Voting in the UN General Assembly" Routledge Handbook of International Organization, edited by Bob Reinalda (published May 27, 2013). Available at SSRN: http://ssrn.com/abstract=2111149

Here is the code to read in each data set. You can find the description online in the instructions. 

**Add code below to suppress the message output from reading in the data (there are several ways to do this).**

```{r}
#| label: load-all-data
unvotes <- read_csv("https://raw.githubusercontent.com/statistical-computing-r/spring-2026/refs/heads/main/group-activities/week-9/data/unvotes.csv")

roll_calls <- read_csv("https://raw.githubusercontent.com/statistical-computing-r/spring-2026/refs/heads/main/group-activities/week-9/data/roll_calls.csv")

issues <- read_csv("https://raw.githubusercontent.com/statistical-computing-r/spring-2026/refs/heads/main/group-activities/week-9/data/issues.csv")
```


**What variable(s) do each of these data frames have in common?**

>Insert Answer Here  


<!-- Swap roles -- Computer becomes Coder, Coder becomes Computer! -->

## Data Exploration
Our goal today is to explore how various members (countries) in the United Nations vote. We have three data sets, what can we determine from each data set separately?


### UN Votes

The first data set, `unvotes` contains data on the `rcid` which is the roll call id for the vote, the country/country code, and how the country voted. What can we learn from the data?  

Comment on the following code, what is happening in each line?  One way to approach seeing what each line does is to highlight the code from before the `pipe` of that line up to the data `unvotes` and use `CTRL + ENTER` to run just the highlighted lines.  

```{r}
#| label: unvotes-graph
unvotes |> 
  count(country, vote) |> #comment
  group_by(country) |> #comment
  mutate(total = sum(n)) |> #comment 
  mutate(prop_vote = n/total) |> #comment
  filter(country %in% c("United States", "Canada", 
                        "Germany", "France",
                        "Italy", "Japan",
                        "United Kingdom")) |> #comment
  ggplot(aes(y = country, x = prop_vote, 
             fill = vote)) + #comment
  geom_col(position = position_stack()) + #comment
  labs(y = "Group of Seven Countries",
       x = "Proportion of Votes",
       title = "Voting Record of the G7",
       fill = "Vote") + #comment
  theme_minimal() +  #comment
  scale_fill_viridis_d(end = 0.8) 
```

**Describe what the graph above demonstrates above UN voting records for the G7.** 
  
>Insert Answer Here  
  
  

<!-- Swap roles -- Computer becomes Coder, Coder becomes Computer! -->




### Roll Calls

The second data set, `roll_calls` has more information on the type of vote, the importance, whether it was a resolution, and date of the vote.  

```{r}
#| label: roll-call-list
roll_calls |> 
  distinct(short)
```


**What does the code above do? What information does it provide? Is it useful?**

>Insert Answer Here



We can use the individual data for `roll_calls` to look at the number of votes per year over time.

```{r}
roll_calls |> 
  mutate(year = lubridate::year(date)) |> #extracts the year from the date value and creates a new `year` column
  count(year) |> #counts how many votes there were per year assuming each line is an single voting instance
  ggplot(aes(x = year, y = n)) +
  geom_line() +
  labs(x = "Year", y = "Number of Votes",
       title = "UN Votes per Year") +
  theme_minimal()
```



**What information is missing from the above graphic that might be useful in understanding the issues the UN commonly votes on?**

>Insert Answer Here



<!-- Swap roles -- Computer becomes Coder, Coder becomes Computer! -->


### Issues 

Finally we have the `issues` data which provides a more general description for each vote on specific issues.  Note that not all issues are included in the data set, just the ones related to the 6 issues below:

```{r}
#| label: count-issues
issues |> 
  count(issue) |> 
  adorn_totals("row") #from janitor package
```

Notice the size of the issues data - it has 5745 rows, but if look at the distinct number of roll call identification numbers, you will see that there are 4099, meaning that more than one issue can be associated with the same roll call id/vote. 

```{r}
#| label: distinct-issues-rcid
issues |> 
  distinct(rcid) |> 
  n_distinct()
```

Recall that in `roll_call` there are 6202 distinct roll call ids/votes, so the issues associated with `issues` do not represent all votes (i.e., there were other U.N. votes on other issues than our 6 chosen issues).  

```{r}
#| label: distinct-issues-rcid
roll_calls |> 
  distinct(rcid) |> 
  n_distinct()
```

It would be helpful to use the `issues` data with the `roll_calls` data to be able to better understand the voting trends within the UN on these 6 issues. To do this, we need to join the data.  



# Votes Over Time  

Now let's join our data together to get a better idea of how the UN has voted over time.  
First, look at the number of rows in `issues` and `roll_calls` - do they match? What does this indicate?

```{r}
#| label: check-dimensions
dim(issues)
dim(roll_calls)
```


Now let's try joining the `roll_calls` with the `issues` data.  Compare the following codes to join the data. Describe what each one does and how it differs from the others as a comment in the code chunk.  You might need to reference the slides or reading for this week.

```{r}
#| label: left-join
#| message: true
#| warning: true
#| eval: false
roll_calls |> 
  left_join(issues, by = "rcid") #description of join
```

```{r}
#| label: right-join
#| message: true
#| warning: true
#| eval: false
roll_calls |> 
  right_join(issues, by = "rcid") #description of join
```

```{r}
#| label: full-join
#| message: true
#| warning: true
#| eval: false
roll_calls |> 
  full_join(issues, by = "rcid") #description of join
```

```{r}
#| label: inner-join
#| message: true
#| warning: true
#| eval: false
roll_calls |> 
  inner_join(issues, by = "rcid") #description of join
```


**If we are only interested in retaining the records associated with the `issues` labeled in that data frame, ignoring the other votes, which join should we use?**

> Insert answer here




<!-- Swap roles -- Computer becomes Coder, Coder becomes Computer! -->


Now that we know how to join the data, we will use the following code to examine the the voting trends for three of the issues related to conflict/weapons. 

Be sure to run the code via the green arrow on the code chunk, as the `case_when()` code can get finicky sometimes and claim an error about a comma in the code when it doesn't exist.  *Comment on the code where indicated* and add your chosen join function


```{r}
#| label: votes-on-conflicts-graph
roll_calls |> 
 __________join(issues, by = "rcid") |>  #join roll_calls and issues so that just the votes related to the issues data are retained.
  mutate(issue_short = case_when(
    issue == "Arms control and disarmament" ~ "Arms Control",
    issue == "Nuclear weapons and nuclear material" ~ "Nuclear Weapons",
    issue == "Palestinian conflict" ~ "Palestinian Conflict",
    TRUE ~ issue)) |>   #what is happening in this mutate function?
  filter(issue_short %in% c("Arms Control",
                            "Nuclear Weapons",
                            "Palestinian Conflict")) |> #what are we doing here?
  mutate(year = lubridate::year(date)) |> #create a column `year` that contains the year value
  count(year, 
        issue_short) |> #what does this line do?
  ggplot(aes(x = year, 
             y = n, 
             group = issue_short)) + #what does this line do?
  geom_line(aes(color = issue_short)) + #what does this line do?
  labs(x = "Year", 
       y = "Number of Votes",
       title = "United Nations Votes per Year",
       subtitle = "Conflict and Arms Related Votes",
       color = "Voting Issue") +
  theme_minimal() +
  scale_color_viridis_d(end = 0.9)
```



**What do you notice? What do you wonder based on the graph created?**

> Insert answer here


<!-- Swap roles -- Computer becomes Coder, Coder becomes Computer! -->


# Joining all Data

We want to try and create the the visualization in the online instructions. To do this, though, we need information from all three data set, `unvotes`, `issues`, and `roll_calls`

We want to join all three data sets together, *maintaining only the votes for which we have identified the general issue* (e.g., Nuclear War, Arms, Economics, etc.), but recognizing that each `rcid` will match MULTIPLE rows in the `unvotes` because we have each individual country's vote.  We will save (assign) the data as `un_full`.  

```{r}
#| label: join-all
un_full <- roll_calls |> 
  right_join(issues, by = "rcid") |> 
  left_join(unvotes, by = "rcid", 
            multiple = "all", 
            relationship = "many-to-many") 
```


**Describe what each join is doing and why each join has specific arguments. Hint: look at the link in the online instructions.**

> Insert answer here


Now, we are going to do some data cleaning.  Our goal is create a data set that includes the percentage of "yes" votes per country each year. We will call the data table `yes_votes`. *Provide a comment to describe what each line of code is doing in the process*.  

```{r}
#| label: yes-votes-cleaning
yes_votes <- un_full |> 
  select(country, 
         issue, 
         date, 
         vote) |>  # your comment here
  mutate(year = lubridate::year(date)) |> #create a new variable called year
  group_by(country, 
           year, 
           issue) |> # your comment here
  summarize(prop_yes = mean(vote == "yes"), 
            .groups = "drop_last") |> #calculate the proportion of yes votes
  mutate(issue = case_when(
    issue == "Arms control and disarmament" ~ "Arms Control",
    issue == "Nuclear weapons and nuclear material" ~ "Nuclear Weapons",
    issue == "Palestinian conflict" ~ "Palestinian Conflict",
    TRUE ~ issue)) # your comment here

#View(yes_votes) #you can use this code to look at the table created
```

<!-- Swap roles -- Computer becomes Coder, Coder becomes Computer! -->


Now we can feed the `yes_votes` transformed data table into your graphing code, but first we will want to focus on the United States and Canada. *Provide a comment to describe what each line of code is doing in the process*.  

```{r}
#| label: yes-votes-canada-us
yes_votes |> 
  filter(country %in% c("United States","Canada")) |> # your comment here
  ggplot(mapping = aes(x = year, y = prop_yes, color = country)) + # your comment here
  geom_point(alpha = 0.4) + # your comment here
  #geom_line(aes(group = country)) +
  geom_smooth(method = "loess", se = FALSE) + #this fits a special model called a loess regression, a smooth line that fits the data
  facet_wrap(~issue) + # your comment here
  scale_y_continuous(labels = scales::percent) + #your comment here
  labs(
    title = "Percentage of 'Yes' votes in the UN General Assembly",
    subtitle = "1946 to 2019",
    y = "% Yes",
    x = "Year",
    color = "Country"
  ) + #your comment here
  theme_bw() +
  theme(legend.position = "bottom") + #your comment here 
  scale_color_viridis_d(option = "turbo") #your comment here
```


**What do you notice about the voting records over time?**

>Insert your Answer Here



Check out the demonstration of even more joins online.  