# Quant Camp Day 1: intro + visualization ------------------------------------
#
# This is the file we fill in together during the morning lecture. Save it
# inside your camp project as code/01-code.R and run it chunk by chunk.


# Packages ---------------------------------------------------------------------

# install anything we are missing (only happens the first time)
needed = c("tidyverse", "gapminder", "socviz", "here", "remotes")
missing = needed[!needed %in% rownames(installed.packages())]
if (length(missing) > 0) install.packages(missing)

# juanr lives on GitHub, not CRAN, so it needs remotes to install
if (!requireNamespace("juanr", quietly = TRUE)) {
  remotes::install_github("hail2thief/juanr")
}

library(tidyverse)   # plotting + data wrangling
library(gapminder)   # country-year data on health and wealth
library(socviz)      # the General Social Survey (gss_lon)
library(juanr)       # evictions, afrobarometer
library(here)        # file paths that work on any computer


# 1. Is this a project? --------------------------------------------------------

# this should print the folder that contains rproject_camp.Rproj
# if it doesn't, close RStudio and double-click the .Rproj file
here()


# 2. Your first script ---------------------------------------------------------

# open code/plot-un-votes.R and run it top to bottom, then do the three
# modifications on the slide:
#   1. change the countries (find where they are chosen)
#   2. rename the output file to something informative
#   3. start claude in the project folder and ask it to make the plot prettier


# 3. How to plot data: the Gapminder build-up ----------------------------------

# look at the data and its codebook
gapminder
?gapminder

# subset to 2007
gap_07 = gapminder |>
  filter(year == 2007)

# build the plot one layer at a time
ggplot(data = gap_07)

ggplot(data = gap_07, aes(x = gdpPercap, y = lifeExp))

ggplot(data = gap_07, aes(x = gdpPercap, y = lifeExp)) +
  geom_point()

# map population to size, continent to color
ggplot(data = gap_07, aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) +
  geom_point()

# add titles with labs()
ggplot(data = gap_07, aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) +
  geom_point() +
  labs(x = "GDP per capita", y = "Life expectancy",
       title = "Global wealth and health in 2007",
       size = "Population", color = NULL)


# 🚨 Your turn: label the points -----------------------------------------------

# 1. map country names onto the label aesthetic inside aes()
# 2. add a geom_text() layer
# 3. ask claude to change the plot so only ONE country is highlighted



# 4. The four key graphs -------------------------------------------------------

# (a) scatterplot: relationship between two continuous variables
ggplot(gap_07, aes(x = gdpPercap, y = lifeExp)) +
  geom_point(size = 1.5) +
  labs(x = "GDP per capita", y = "Life expectancy")


# (b) time series: a variable over time
# evictions in NYC, one row per eviction; count them by month (Day 2 covers this)
evict_month = evictions |>
  mutate(month = floor_date(date, "month")) |>
  count(month)

ggplot(evict_month, aes(x = month, y = n)) +
  geom_line(linewidth = 1.8) +
  labs(x = NULL, y = "Evictions per month",
       title = "Evictions carried out in New York City")

# a cliff in early 2020: did the world change, or did the data change?
# (the plot can't tell you; go find out before you compute a "2020 average")

# multiple time series: one line per country
gapminder_sample = gapminder |>
  filter(country == "Bolivia" | country == "China" | country == "Germany")

# each row is a country-year, so every year shows up three times
head(gapminder_sample)

# one line: R connects ALL the points in order of year, so it zigzags
# between countries. Nothing told it which rows belong together
ggplot(data = gapminder_sample, aes(x = year, y = lifeExp)) +
  geom_line()

# group = country: separate lines, but no legend
ggplot(data = gapminder_sample, aes(x = year, y = lifeExp, group = country)) +
  geom_line()

# color = country: separate lines AND a legend
# recipe: time on x, the variable on y, the unit (country) on color
ggplot(data = gapminder_sample, aes(x = year, y = lifeExp, color = country)) +
  geom_line(linewidth = 1.4) +
  labs(y = "Life expectancy (years)", x = NULL, color = "Country:",
       title = "Life expectancy over time in Bolivia, China, and Germany")


# 🚨 Your turn: recession -------------------------------------------------------

# the economics data (comes with the tidyverse)
economics
?economics

# 1. make a time series of unemployment over time
# 2. can you find the recessions?
# 3. have your agent plot the other variable side-by-side with your plot.
#    look at what it added to your code



# (c) histogram: the distribution of one continuous variable
# survey weights in the General Social Survey: how many people each
# respondent "stands for". The average is 1 by construction
weights = gss_lon |>
  filter(!is.na(wtssall))

ggplot(weights, aes(x = wtssall)) +
  geom_histogram(color = "white", binwidth = .25) +
  labs(x = "Survey weight (1 = counts as one person)", y = "Respondents",
       title = "Survey weights in the General Social Survey")

# why does the axis go to 9? a few respondents count as eight people.
# who are they? (the histogram finds them; the codebook explains them)
weights |>
  filter(wtssall > 4) |>
  arrange(desc(wtssall)) |>
  select(year, age, sex, marital, wtssall)

# the default is 30 bins; binwidth = .25 or bins = 50 changes how fine it is
ggplot(weights, aes(x = wtssall)) +
  geom_histogram()


# 🚨 Your turn: organs ----------------------------------------------------------

# organ donation data (from socviz)
organdata
?organdata

# 1. histogram of the donation rate (donors)
# 2. grouped histogram, by whether donors opt in or opt out (opt)
# 3. ask claude to mark the country with the highest donation rate



# (d) barplot: count a categorical variable
# Afrobarometer, Ethiopia 2020: attended a protest in the past year (0 to 4)
# the numbers 0 to 4 get their labels from the codebook (?afrobarometer)
protest = afrobarometer |>
  filter(!is.na(protest)) |>
  mutate(protest = factor(protest, levels = 0:4,
    labels = c("No, would never", "No, but would if I could",
               "Yes, once or twice", "Yes, several times", "Yes, often")))

# geom_bar() counts the rows in each category for you
# (geom_col() is for when you already have the numbers)
ggplot(protest, aes(y = protest)) +
  geom_bar(color = "white") +
  labs(y = NULL, x = "Respondents",
       title = "Attended a protest in the past year, Ethiopia (2020)")

# where do you draw the line? five answers is often too many; we want two.
# the three "yes" bars are small alone but a quarter of the sample together,
# so the cut that makes sense is protested vs. did not (Day 2: case_when())


# 5. Save a plot ---------------------------------------------------------------

# ggsave() saves the LAST plot you made; here() builds the path
ggsave(here("figures", "protest_ethiopia.png"), width = 8, height = 5)
