# name: equivalence2.R
# author: scott cunningham  
# description: OLS and Manual are the same

# Load required libraries
library(haven)
library(dplyr)
library(fixest)
library(tidyr)

# Clear workspace and load data
rm(list = ls())

# Load the castle dataset
castle <- read_dta("https://github.com/scunning1975/mixtape/raw/master/castle.dta")

# Set up panel structure (equivalent to xtset)
castle <- castle %>%
  arrange(sid, year)

# Drop specific years and create variables
castle <- castle %>%
  filter(!(effyear %in% c(2005, 2007, 2008, 2009))) %>%
  select(-post) %>%
  mutate(
    post = ifelse(year >= 2006, 1, 0),
    treat = ifelse(effyear == 2006, 1, 0)
  ) %>%
  filter(year %in% c(2005, 2006))

# Example 1: OLS regression with interactions
cat("Example 1: OLS regression with interactions\n")
model1 <- feols(l_homicide ~ post * treat, 
                data = castle, 
                cluster = ~sid)
summary(model1)

# Example 2: Twoway fixed effects (state and year fixed effects)
cat("\nExample 2: Twoway fixed effects (state and year fixed effects)\n")
model2 <- feols(l_homicide ~ treat:post + factor(year) | sid, 
                data = castle, 
                cluster = ~sid)
summary(model2)

# Example 3: Regress "long difference" onto treatment dummy
cat("\nExample 3: Regress 'long difference' onto treatment dummy\n")

# Create the difference data (removing prison variable that doesn't exist)
diff_data <- castle %>%
  select(sid, year, l_homicide, treat) %>%
  pivot_wider(
    names_from = year,
    values_from = l_homicide,
    names_prefix = "l_homicide_"
  ) %>%
  mutate(
    diff = l_homicide_2006 - l_homicide_2005
  )

model3 <- feols(diff ~ treat, 
                data = diff_data, 
                cluster = ~sid)
summary(model3)

