#################################################
## POL269: POLITICAL DATA RESEARCH
## LECTURE 4: EXPLORING ONE VARIABLE AT A TIME
#################################################

## STEP 1. Set the working directory
setwd("~/Desktop/POL269") # if Mac 
setwd("C:/user/Desktop/POL269") # if Windows

## STEP 2. Load the dataset and tidyverse
library(tidyverse) # loads the tidyverse package
voting <- read.csv("voting.csv") # reads and stores data

## STEP 3. Look at the data
head(voting) # shows the first six observations
## what's the unit of observation?
## for each variable: type and unit of measurement?
## substantively interpret the first observation

## STEP 4. Explore one variable at a time
## create frequency table of voted
table(voting$voted)
# OR
voting %>%
  count(voted)

## create table of proportions of voted
prop.table(table(voting$voted))
# OR
voting %>%
  count(voted) %>%
  mutate(proportion = n / sum(n))

## create histograms 
hist(voting$birth) # of birth
hist(voting$voted) # of voted
# OR
voting %>%
  ggplot(aes(x = birth)) +
  geom_histogram(binwidth = 1) +
  labs(title = "Histogram of birth", x = "Year of birth", y = "Frequency")
voting %>%
  ggplot(aes(x = voted)) +
  geom_histogram(binwidth = 1) +
  labs(title = "Histogram of voted", x = "Voted", y = "Frequency")

## compute means 
mean(voting$birth) # of birth
mean(voting$voted) # of voted
#OR
voting %>%
  summarise(mean_birth = mean(birth), mean_voted = mean(voted))

## compute medians
median(voting$birth) # of birth
median(voting$voted) # of voted
# OR
voting %>%
  summarise(median_birth = median(birth), median_voted = median(voted))


## compute the standard deviation of birth
sd(voting$birth)
# OR
voting %>%
  summarise(sd_birth = sd(birth))

## compute the variance of birth
var(voting$birth)
sd(voting$birth)^2 # alternative code
# OR
voting %>%
  summarise(var_birth = var(birth))
