library(haven)
library(dplyr)

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

# View column names to confirm
print(colnames(data))

# Split data into treated and control groups
treated <- data %>% filter(treat == 1)
control <- data %>% filter(treat == 0)

# Initialize a matrix to store distances
distance_matrix <- matrix(NA, nrow = nrow(treated), ncol = nrow(control))

# Calculate pairwise Euclidean distances
for (i in 1:nrow(treated)) {
  for (j in 1:nrow(control)) {
    distance_matrix[i, j] <- sqrt((treated$age[i] - control$age[j])^2 +
                                    (treated$gpa[i] - control$gpa[j])^2)
  }
}

# Find the index of the nearest control for each treated unit
nearest_control_indices <- apply(distance_matrix, 1, which.min)

# Extract matched control observations
matched_control <- control[nearest_control_indices, ]

# Combine treated and matched control units
matched_data <- cbind(
  treated %>% dplyr::select(unitid, age, gpa, earnings),
  matched_control %>% dplyr::select(unitid, age, gpa, earnings) %>%
    rename(Control_Unit = unitid, Control_Age = age, Control_GPA = gpa, Control_Earnings = earnings)
)

# Calculate differences and ATT
matched_data <- matched_data %>%
  mutate(Distance = sqrt((age - Control_Age)^2 + (gpa - Control_GPA)^2),
         Earnings_Diff = earnings - Control_Earnings)

# Calculate ATT
att_manual <- mean(matched_data$Earnings_Diff)
print(matched_data)
print(paste("Manual ATT =", round(att_manual, 2)))