Skip to content

Instantly share code, notes, and snippets.

@vankesteren
Last active November 15, 2022 20:23
Show Gist options
  • Save vankesteren/24a4fc573d1d47b4a38e619dd6bb4ee4 to your computer and use it in GitHub Desktop.
Save vankesteren/24a4fc573d1d47b4a38e619dd6bb4ee4 to your computer and use it in GitHub Desktop.
Performing the synthetic control method using glmnet. This allows easily validating the model using LOOCV
# Implementing synthetic control using glmnet
library(tidyverse)
library(tidysynth)
library(glmnet)
# we need a wide dataset, only cigsale
smoking_w <-
smoking |>
select(state, year, cigsale) |>
pivot_wider(names_from = state, values_from = cigsale)
# LOOCV LASSO
X_pre <- model.matrix(California ~ . - year + 0, data = smoking_w |> filter(year <= 1988))
X_post <- model.matrix(California ~ . - year + 0, data = smoking_w |> filter(year > 1988))
y_pre <- smoking_w |> filter(year <= 1988) |> pull(California)
y_post <- smoking_w |> filter(year > 1988) |> pull(California)
cv.fit <- cv.glmnet(X_pre, y_pre, lower.limits = 0, upper.limits = 1, nfolds = nrow(X_pre), grouped = FALSE)
yhat <- predict(cv.fit, newx = rbind(X_pre, X_post), s = "lambda.1se")
plot(x = 1970:2000, y = c(y_pre, y_post), type = "l", xlab = "Year", ylab = "Cigarette sales",
main = "Synthetic control using LASSO", bty = "L")
lines(x = 1970:2000, y = yhat, lty = 2)
mtext("With leave-one-out cross-validation", line = 0.5)
text(2000, tail(y_post, 1), "California", c(1.15, 0))
text(2000, tail(yhat, 1), "Synthetic California", c(1.15, 0))
@vankesteren
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment