### Getting Started with fect Source: https://yiqingxu.org/packages/fect/index A link to the initial guide for using the fect R package, covering basic setup and usage. ```APIDOC Get Started Guide: - URL: https://yiqingxu.org/packages/fect/01-start.html ``` -------------------------------- ### Basic Data Setup and PanelView Visualization Source: https://yiqingxu.org/packages/fect/rscript/04-gsynth Initializes the R environment, loads the 'fect' and 'panelView' libraries, and displays basic data and panel visualizations. This sets up the context for subsequent analyses. ```R set.seed(1234) rm(list = ls()) library(fect) data(fect) ls() head(simgsynth) library(panelView) panelview(Y ~ D, data = simgsynth, index = c("id","time"), pre.post = TRUE) panelview(Y ~ D, data = simgsynth, index = c("id","time"), type = "outcome") ``` -------------------------------- ### fect Package User Guide Structure Source: https://yiqingxu.org/packages/fect/index Outlines the structure of the fect package user guide, detailing the content of each chapter from installation and datasets to advanced topics like sensitivity analysis and a cheatsheet. ```R ## fect User Guide Chapters: - **Chapter @sec-start:** Installation and Datasets. - **Chapter @sec-fect:** Applying five estimators and diagnostic tests from previous fect versions. - **Chapter @sec-plots:** Exploring plotting options. - **Chapter @sec-gsynth:** Implementing original gsynth R package functionalities using fect. - **Chapter @sec-panel:** Applying new DID estimators. - **Chapter @sec-panel-sens:** Sensitivity analysis for counterfactual estimators. - **Chapter @sec-cheatsheet:** Summary of core inputs, plotting, and diagnostics for six methods. ``` -------------------------------- ### Install and Load fect Package Source: https://yiqingxu.org/packages/fect/rscript/06-sens Installs the 'fect' package from GitHub and loads it along with other necessary libraries. It also includes a function to install multiple packages if they are not already installed. ```R rm(list = ls()) install.packages("fect") devtools::install_github("xuyiqing/fect") installed.packages()["fect", "Version"] devtools::install_github('xuyiqing/panelView') install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) library(fect) data(fect) ls() ``` -------------------------------- ### Report Bugs and Get Support Source: https://yiqingxu.org/packages/fect/index Instructions on how to report bugs and seek support for the fect package. It recommends reporting to the author via email or submitting an issue on GitHub, and emphasizes the importance of including a reproducible code example and a panelView plot. ```APIDOC Bug Reporting: - Email: yiqingxu [at] stanford.edu - GitHub Issues: https://github.com/xuyiqing/fect/issues Required Information for Bug Reports: - Minimally replicable code - Data file - panelView treatment status plot Feedback is highly valued. ``` -------------------------------- ### Install panelView from GitHub Source: https://yiqingxu.org/packages/fect/01-start Installs the panelView package from GitHub, which is recommended for panel data visualization and used in the fect tutorial. ```R devtools::install_github('xuyiqing/panelView') ``` -------------------------------- ### Install fect from GitHub Source: https://yiqingxu.org/packages/fect/01-start Installs the most up-to-date version of the 'fect' package directly from its GitHub repository. Requires the devtools package. ```r devtools::install_github("xuyiqing/fect") ``` -------------------------------- ### Install panelView from GitHub Source: https://yiqingxu.org/packages/fect/01-start Installs the 'panelView' package from GitHub, which is recommended for panel data visualization and used in the tutorial. Requires the devtools package. ```r devtools::install_github('xuyiqing/panelView') ``` -------------------------------- ### Install and Load fect Package Source: https://yiqingxu.org/packages/fect/rscript/04-gsynth Installs the 'fect' package from CRAN and GitHub, checks its version, and loads it along with its data. It also includes a helper function to install multiple packages if they are not already installed. ```R rm(list = ls()) install.packages("fect") devtools::install_github("xuyiqing/fect") installed.packages()["fect", "Version"] devtools::install_github('xuyiqing/panelView') install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) library(fect) data(fect) ls() ``` -------------------------------- ### Install All Dependencies Source: https://yiqingxu.org/packages/fect/01-start A custom R function to install a list of specified packages if they are not already installed. This ensures all necessary packages for 'fect' are available. ```r install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) ``` -------------------------------- ### Install All Dependent Packages Source: https://yiqingxu.org/packages/fect/01-start A helper function to install all necessary dependent packages for fect if they are not already installed. It checks for existing installations before attempting to install. ```R install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) ``` -------------------------------- ### Install and Load fect Package Source: https://yiqingxu.org/packages/fect/rscript/02-fect Installs the 'fect' package from CRAN and GitHub, checks its version, and loads the package and its data. It also includes a helper function to install multiple packages if they are not already installed. ```r rm(list = ls()) install.packages("fect") devtools::install_github("xuyiqing/fect") installed.packages()["fect", "Version"] devtools::install_github('xuyiqing/panelView') install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) library(fect) data(fect) ls() ``` -------------------------------- ### Install fect from GitHub Source: https://yiqingxu.org/packages/fect/01-start Installs the latest development version of the fect package directly from GitHub. Requires the devtools package. ```R devtools::install_github("xuyiqing/fect") ``` -------------------------------- ### Install and Load fect Package Source: https://yiqingxu.org/packages/fect/rscript/05-panel Installs the 'fect' package from CRAN and GitHub if not already installed, and then loads it along with other necessary packages for data analysis. It also demonstrates loading the 'fect' dataset. ```R rm(list = ls()) install.packages("fect") devtools::install_github("xuyiqing/fect") installed.packages()["fect", "Version"] devtools::install_github('xuyiqing/panelView') install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) library(fect) data(fect) ls() ``` ```R # install packages from CRAN packages <- c("dplyr", "fixest", "did", "didimputation", "panelView", "ggplot2", "bacondecomp", "HonestDiD", "DIDmultiplegtDYN", "PanelMatch") install.packages(setdiff(packages, rownames(installed.packages()))) # install most up-to-date "fect" from Github if ("fect" %in% rownames(installed.packages()) == FALSE) { devtools:: install_github("xuyiqing/fect") } library(dplyr) library(readstata13) library(fixest) library(did) library(fect) library(panelView) library(PanelMatch) library(ggplot2) library(bacondecomp) library(fect) library(didimputation) library(doParallel) library(HonestDiD) library(HonestDiDFEct) library(DIDmultiplegtDYN) # may require XQuartz data(fect) data <- hh2019 head(data) ``` -------------------------------- ### FECT with GSynth Method Source: https://yiqingxu.org/packages/fect/rscript/02-fect Demonstrates the `fect` function with the 'gsynth' (Generalized Synthetic Control) method. This example includes parameters for cross-validation, standard error calculation via bootstrapping, and keeping simulation results. ```R out <- fect(Y ~ D + X1 + X2, data = simgsynth, index = c("id","time"), method = "gsynth", force = "two-way", CV = TRUE, r = c(0, 5), se = TRUE, nboots = 200, vartype = 'bootstrap', parallel = FALSE, keep.sims=TRUE) ``` -------------------------------- ### Install fect and HonestDiDFEct from GitHub Source: https://yiqingxu.org/packages/fect/rscript/06-sens Installs the 'fect' package from GitHub if not already installed, and also installs the 'HonestDiDFEct' package, which is required for the 'fect_sens' function. ```R # install packages from CRAN packages <- c("dplyr", "panelView", "ggplot2") # Removed HonestDiD, doParallel install.packages(setdiff(packages, rownames(installed.packages()))) # install most up-to-date "fect" from Github if ("fect" %in% rownames(installed.packages()) == FALSE) { devtools:: install_github("xuyiqing/fect") } # install forked "HonestDiD" package compatible with "fect" if ("HonestDiDFEct" %in% rownames(installed.packages()) == FALSE) { devtools:: install_github("lzy318/HonestDiDFEct") # This is used by fect_sens } library(dplyr) library(fect) library(panelView) library(ggplot2) library(HonestDiDFEct) # Required for fect_sens to work data(fect) data <- hh2019 head(data) ``` -------------------------------- ### FECT with MC Method Source: https://yiqingxu.org/packages/fect/rscript/02-fect Illustrates the application of the `fect` function using the 'mc' (Matrix Completion) method. This example shows how to specify a lambda value and includes parameters for parallel processing and standard error calculation. ```R out.mc.c <- fect(Y ~ D + X1 + X2, data = simdata, index = c("id", "time"), force = "two-way", method = "mc", lambda = out.mc$lambda.cv, CV = 0, parallel = TRUE, se = TRUE, nboots = 200, carryoverTest = TRUE, carryover.period = c(1, 3)) ``` -------------------------------- ### Install CRAN and GitHub Packages Source: https://yiqingxu.org/packages/fect/05-panel Installs specified R packages from CRAN and the latest 'fect' and 'HonestDiDFEct' packages from GitHub. It checks if packages are already installed before attempting installation. ```R packages <- c("dplyr", "fixest", "did", "didimputation", "panelView", "ggplot2", "bacondecomp", "HonestDiD", "DIDmultiplegtDYN", "PanelMatch") install.packages(setdiff(packages, rownames(installed.packages()))) if ("fect" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("xuyiqing/fect") } if ("HonestDiDFEct" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("lzy318/HonestDiDFEct") } ``` -------------------------------- ### Install and Load fect Package Source: https://yiqingxu.org/packages/fect/rscript/03-plot Installs the 'fect' package from CRAN and GitHub, checks its version, and loads it into the R session. It also installs a list of common data analysis packages if they are not already installed. ```R rm(list = ls()) install.packages("fect") devtools::install_github("xuyiqing/fect") installed.packages()["fect", "Version"] devtools::install_github('xuyiqing/panelView') install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("abind", "doParallel", "doRNG", "fixest", "foreach", "future", "GGally", "ggplot2", "grid", "gridExtra", "Mass", "panelView", "Rcpp") install_all(packages) library(fect) data(fect) ls() ``` -------------------------------- ### Install fect Packages Source: https://yiqingxu.org/packages/fect/05-panel Installs the necessary fect packages from CRAN and GitHub to perform causal panel analysis and implement various DID estimators. ```R install.packages("fect") # Or from GitHub: # devtools::install_github("yiqingxu/fect") ``` -------------------------------- ### Install fect from CRAN Source: https://yiqingxu.org/packages/fect/01-start Installs the fect package from the Comprehensive R Archive Network (CRAN). This is the standard method for installing R packages. ```R install.packages("fect") ``` -------------------------------- ### Install fect from CRAN Source: https://yiqingxu.org/packages/fect/01-start Installs the 'fect' package from the Comprehensive R Archive Network (CRAN). This is the standard method for installing R packages. ```r install.packages("fect") ``` -------------------------------- ### Gsynth with Bootstrap Uncertainty Source: https://yiqingxu.org/packages/fect/04-gsynth Example of running the gsynth method with bootstrap for uncertainty estimates. It includes parallel processing and specifies the number of cores. ```r system.time( out <- fect(Y ~ D + X1 + X2, data = simgsynth, index = c("id","time"), method = "gsynth", force = "two-way", CV = TRUE, r = c(0, 5), se = TRUE, nboots = 1000,vartype = 'parametric', parallel = TRUE, cores = 16) ) ``` -------------------------------- ### Check fect Version Source: https://yiqingxu.org/packages/fect/01-start Retrieves and displays the installed version of the 'fect' package. Useful for verifying installation and ensuring the package is up-to-date. ```r installed.packages()["fect", "Version"] ``` -------------------------------- ### Install and Load fect Packages Source: https://yiqingxu.org/packages/fect/06-sens Installs necessary R packages from CRAN and GitHub, including the fect package and its compatible HonestDiDFEct fork. It then loads these libraries for use in sensitivity analysis. ```r packages <- c("dplyr", "panelView", "ggplot2") install.packages(setdiff(packages, rownames(installed.packages()))) if ("fect" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("xuyiqing/fect") } if ("HonestDiDFEct" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("lzy318/HonestDiDFEct") # This is used by fect_sens } library(dplyr) library(fect) library(panelView) library(ggplot2) library(HonestDiDFEct) # Required for fect_sens to work ``` -------------------------------- ### Install and Load fect Packages Source: https://yiqingxu.org/packages/fect/06-sens Installs required R packages from CRAN and GitHub, including 'fect' and 'HonestDiDFEct', and then loads them into the R session for use in sensitivity analysis. ```R # install packages from CRAN packages <- c("dplyr", "panelView", "ggplot2") install.packages(setdiff(packages, rownames(installed.packages()))) # install most up-to-date "fect" from Github if ("fect" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("xuyiqing/fect") } # install forked "HonestDiD" package compatible with "fect" if ("HonestDiDFEct" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("lzy318/HonestDiDFEct") # This is used by fect_sens } library(dplyr) library(fect) library(panelView) library(ggplot2) library(HonestDiDFEct) # Required for fect_sens to work ``` -------------------------------- ### FEfect gsynth with Data Subsetting and PanelView Source: https://yiqingxu.org/packages/fect/rscript/04-gsynth Prepares a subset of the turnout data by removing specific rows and then applies the gsynth method. Includes a panelView visualization of the subsetted data. ```R set.seed(123456) turnout.ub <- turnout[-c(which(turnout$abb=="WY")[1:15], sample(1:nrow(turnout),50,replace=FALSE)),] panelview(turnout ~ policy_edr + policy_mail_in + policy_motor, data = turnout.ub, index = c("abb","year"), pre.post = TRUE) out_ub <- fect(turnout ~ policy_edr + policy_mail_in + policy_motor, data = turnout.ub, index = c("abb","year"), se = TRUE, method = "gsynth", r = c(0, 5), CV = TRUE, force = "two-way", parallel = TRUE, min.T0 = 8, nboots = 1000, seed = 02139) plot(out_ub, type = "status", xticklabels=c(1920, 1928, 1936, 1944, 1952, 1960, 1968, 1976, 1984, 1992, 2000, 2008), xangle=10) ``` -------------------------------- ### Gsynth with Jackknife Uncertainty Source: https://yiqingxu.org/packages/fect/04-gsynth Example of running the gsynth method using the jackknife method for uncertainty estimates. It also utilizes parallel processing. ```r out2 <- fect(Y ~ D + X1 + X2, data = simgsynth, index = c("id","time"), method = "gsynth", force = "two-way", CV = TRUE, r = c(0, 5), se = TRUE, vartype = "jackknife", parallel = TRUE, cores = 16) ``` -------------------------------- ### Cohort Analysis with get.cohort Source: https://yiqingxu.org/packages/fect/rscript/02-fect Shows how to use the `get.cohort` function to create cohort variables from panel data. It demonstrates creating cohorts based on treatment entry and handling different entry time specifications. ```R simdata.cohort <- get.cohort(data = simdata,D = 'D',index = c("id","time")) print(table(simdata.cohort[,'Cohort'])) simdata.cohort2 <- get.cohort(data = simdata,D = 'D',index = c("id","time"), entry.time = list(c(21,27),c(30,33))) print(table(simdata.cohort2[,'Cohort'])) ``` -------------------------------- ### Accessing fect Results Source: https://yiqingxu.org/packages/fect/02-fect These examples show how to access specific estimated results from the `out.fect` object, including estimated ATT, average effects, and beta coefficients. ```r out.fect$est.att out.fect$est.avg out.fect$est.beta ``` -------------------------------- ### Flagging Units with Negative Change in Treatment Source: https://yiqingxu.org/packages/fect/rscript/03-plot Example of using `tapply` to identify units where the treatment variable shows a decrease over time. ```R # flag units that ever have a 1 to 0 change in d rev_flag <- tapply(gs2020[["cand_A_all"]], gs2020[["district_final"]], function(x) any(diff(x) < 0)) ``` -------------------------------- ### Panel Data Visualization with panelView Source: https://yiqingxu.org/packages/fect/rscript/02-fect Demonstrates how to visualize panel data using the panelView function from the panelView package. It shows how to plot treatment status and outcomes over time for different units. ```R library(panelView) panelview(Y ~ D, data = simdata, index = c("id","time"), axis.lab = "time", xlab = "Time", ylab = "Unit", gridOff = TRUE, by.timing = TRUE, background = "white", main = "Simulated Data: Treatment Status") panelview(Y ~ D, data = simdata, index = c("id","time"), axis.lab = "time", xlab = "Time", ylab = "Unit", theme.bw = TRUE, type = "outcome", main = "Simulated Data: Outcome") ``` -------------------------------- ### Customizing Plot Time Axis Source: https://yiqingxu.org/packages/fect/rscript/03-plot Illustrates how to customize the time axis of the plots, including shifting the start point and setting specific limits and labels. ```R plot(out, start0 = TRUE, # Shift time so treatment begins at 0 main = "Custom Starting Period") ``` ```R plot(out, xlim = c(-10, 1), # only show time periods -8 to 1 ylim = c(-0.15, 0.30), # set y-range xlab = "Custom Time Axis", # x-axis label ylab = "Estimated ATT", # y-axis label xangle = 90, # rotate x-axis labels by 90° xbreaks = seq(-10, 1, by = 2), gridOff = TRUE, # Label x-axis from -12 to 1 with a break of 2 main = "Axis and Legend Customization") ``` -------------------------------- ### Load and Inspect Simulated Data Source: https://yiqingxu.org/packages/fect/02-fect Loads the 'fect' package and the 'simdata' dataset, then lists the available objects. This is a common first step for data analysis. ```R library(fect) data(simdata) ls() #> [1] "gs2020" "hh2019" "simdata" "simgsynth" "turnout" ``` -------------------------------- ### FECT Model with Placebo Test Source: https://yiqingxu.org/packages/fect/rscript/03-plot This example shows how to run a `fect` model with a placebo test enabled. It specifies the placebo period and then plots the results of the placebo test. ```R out_fe_placebo <- fect(Y = "general_sharetotal_A_all", D = "cand_A_all", X = c("cand_H_all", "cand_B_all"), data = gs2020, index = c("district_final", "cycle"), force = "two-way", method = "fe", CV = FALSE, parallel = TRUE, se = TRUE, nboots = 1000, placeboTest = TRUE, placebo.period = c(-2, 0)) plot(out_fe_placebo) ``` -------------------------------- ### FEfect gsynth with Parametric Variance and Simulation Source: https://yiqingxu.org/packages/fect/rscript/04-gsynth Performs gsynth analysis on turnout data with parametric variance estimation and keeps simulation results. Includes plotting and analysis of implied weights. ```R out_turnout <- fect(turnout ~ policy_edr + policy_mail_in + policy_motor, data = turnout, index = c("abb","year"), se = TRUE, method = "gsynth", vartype = "parametric", r = c(0, 5), CV = TRUE, force = "two-way", nboots = 1000, seed = 02139, keep.sims = TRUE) dim(out_turnout$wgt.implied) sort(out_turnout$wgt.implied[,8]) plot(out_turnout, xlim = c(-10, 5), ylim=c(-15,15)) plot(out_turnout, type = "status",xlab = "Year", ylab = "State", main = "Treatment Status", xticklabels=c(1920, 1928, 1936, 1944, 1952, 1960, 1968, 1976, 1984, 1992, 2000, 2008), xangle=10) plot(out_turnout, type = "counterfactual") plot(out_turnout, type = "counterfactual", id = "WI", main = "Wisconsin") plot(out_turnout, type = "box", xticklabels=c("-20", "-15", "-10", "-5","0","5","10")) plot(out_turnout, type = "calendar", ylim = c(-15,15)) plot(out_turnout, type = "factors", xlab = "Year") plot(out_turnout, type = "loadings") ``` -------------------------------- ### FECT with MC Method and Effect Plotting Source: https://yiqingxu.org/packages/fect/rscript/02-fect Applies the `fect` function with the 'mc' method and then plots the resulting effects. This example also shows how to use the `effect` function with the output of the 'mc' method. ```R out_mc <- fect(Y ~ D + X1 + X2, data = simgsynth, index = c("id","time"), method = "mc", force = "two-way", CV = TRUE, r = c(0, 5), se = TRUE, nboots = 200, vartype = 'bootstrap', parallel = FALSE, keep.sims=TRUE) plot(effect(out_mc)) ``` -------------------------------- ### Load fect package and data Source: https://yiqingxu.org/packages/fect/04-gsynth Demonstrates how to load the 'fect' R package and its associated datasets, 'simgsynth' and 'turnout', for use in Gsynth analysis. It also shows how to list the available datasets. ```R library(fect) data(fect) ls() #> [1] "gs2020" "hh2019" "simdata" "simgsynth" "turnout" ``` -------------------------------- ### Load and List fect Datasets Source: https://yiqingxu.org/packages/fect/01-start This snippet demonstrates how to load the 'fect' package and list the datasets it contains. It uses the `library()` function to load the package and the `data()` function to load the datasets, followed by `ls()` to display their names. ```R library(fect) data(fect) ls() ``` -------------------------------- ### MC Method Parameter Tuning Source: https://yiqingxu.org/packages/fect/02-fect Illustrates how to set up the Matrix Completion (MC) method in the `fect` package. It shows how to specify candidate tuning parameters (`lambda`) or let the package generate them automatically based on the outcome variable by setting `nlambda`. ```R # Example of specifying candidate lambda values: # lambda = c(1, 0.8, 0.6, 0.4, 0.2, 0.05) # Example of generating candidate lambda values automatically: # nlambda = 10 ``` -------------------------------- ### FECT Sensitivity Analysis (Relative Magnitude) Source: https://yiqingxu.org/packages/fect/rscript/06-sens Conducts a sensitivity analysis using 'fect_sens' to evaluate the impact of potential unobserved confounders on the estimated treatment effects. This example focuses on the 'Relative Magnitude' restriction, defining parameters for average and period-by-period ATT plots. ```R # Define post-treatment periods and sensitivity parameters for fect_sens T.post <- 10 # Number of post-treatment periods based on original analysis post_periods_vec <- 1:T.post # Parameters for Relative Magnitude (RM) restriction Mbar_vec_avg_rm <- seq(0, 1, by = 0.1) # For average ATT plot Mbar_vec_period_rm <- c(0, 0.5) # For period-by-period ATT plot # Run sensitivity analysis using fect_sens # This function augments out.fect.placebo with sensitivity results out.fect.placebo <- fect_sens( fect.out = out.fect.placebo, post.periods = post_periods_vec, Mbarvec = Mbar_vec_avg_rm, periodMbarvec = Mbar_vec_period_rm, Mvec = NULL, # Not used for RM restriction periodMvec = NULL, # Not used for RM restriction parallel = FALSE # Set to TRUE for parallel processing if desired ) plot(out.fect.placebo, type = "sens", restrict = "rm", main = "Relative Magnitude Restriction") plot(out.fect.placebo, type = "sens_es", restrict = "rm", main = "ATTs with Robust Confidence Sets (RM)", ylab = "Coefficients and 95% CI", xlim = c(-12,10), ylim = c(-6,8), show.count = TRUE) ``` -------------------------------- ### fect Package GitHub Repository Source: https://yiqingxu.org/packages/fect/index Provides access to the source code and algorithms used in the fect package for calculating estimates. Users can explore the implementation details and contribute to the project. ```R https://github.com/xuyiqing/fect ``` -------------------------------- ### fect Package Datasets Source: https://yiqingxu.org/packages/fect/01-start Explanation of datasets used in the fect package, including their origins and applications in various chapters for demonstrating statistical methods like counterfactual estimation and Gsynth. ```R simdata: Based on @LWX2022. Used in [Chapter @sec-fect] to demonstrate various counterfactual estimators. gs2020: Based on @GS2020, who examine the effect of minority candidate presence on the proportion of coethnic donations in U.S. House elections. Used in [Chapter @sec-plots] and [Chapter @sec-panel]. simgsynth & turnout: Based on @Xu2017. Used in [Chapter @sec-gsynth] to demonstrate Gsynth. hh2019: Based on @HH2019, who study the effect of indirect versus direct democracy on naturalization rates in Switzerland. Used in [Chapter @sec-plots], [Chapter @sec-panel] and [Chapter @sec-panel-sens]. ``` -------------------------------- ### Load Fect Package and Data Source: https://yiqingxu.org/packages/fect/02-fect Loads the 'fect' R package and its associated dataset. It also lists the available objects in the environment. ```r library(fect) data(fect) ls() ``` -------------------------------- ### IFEct Method with Cross-Validation Source: https://yiqingxu.org/packages/fect/02-fect Demonstrates how to use the IFEct method with cross-validation to determine the optimal number of factors (r). The example shows setting up the fect function with specified data, formula, index, method, and cross-validation parameters, along with the output indicating the selected optimal r. ```R out.ife <- fect(Y ~ D + X1 + X2, data = simdata, index = c("id","time"), force = "two-way", method = "ife", CV = TRUE, r = c(0, 5), se = TRUE, nboots = 200, parallel = TRUE) #> Parallel computing ... #> Cross-validating ... #> Criterion: Mean Squared Prediction Error #> Interactive fixed effects model... #> r = 0; sigma2 = 6.35460; IC = 2.21891; PC = 6.08178; MSPE = 6.78393 #> r = 1; sigma2 = 4.52698; IC = 2.24325; PC = 5.26760; MSPE = 4.93004 #> r = 2; sigma2 = 3.89603; IC = 2.45349; PC = 5.33953; MSPE = 4.50855 #> * #> r = 3; sigma2 = 3.79056; IC = 2.78325; PC = 5.98062; MSPE = 5.13365 #> r = 4; sigma2 = 3.67967; IC = 3.10762; PC = 6.56967; MSPE = 5.72471 #> r = 5; sigma2 = 3.57625; IC = 3.43005; PC = 7.12886; MSPE = 6.49848 #> #> r* = 2 #> Bootstrapping for uncertainties ... #> 200 runs ``` -------------------------------- ### Citation for fect Package Source: https://yiqingxu.org/packages/fect/06-sens This snippet outlines the recommended citations for the fect package. It includes the primary citation for the sensitivity analysis framework and an optional citation for the tutorial. ```en Please cite Rambachan and Roth ([2023](https://yiqingxu.org/packages/fect/references.html#ref-rambachan2023more)) for their original contribution to the sensitivity analysis framework for causal panel analysis. If you find this tutorial helpful, you can cite Chiu et al. ([2025](https://yiqingxu.org/packages/fect/references.html#ref-CLLX2025)). ``` -------------------------------- ### Load fect Package and Data Source: https://yiqingxu.org/packages/fect/01-start Loads the 'fect' package into the current R session and makes its associated datasets available for use. ```r library(fect) data(fect) ``` -------------------------------- ### Install R Packages for Panel Data Analysis Source: https://yiqingxu.org/packages/fect/05-panel Installs essential R packages for causal panel analysis, including dplyr, fixest, did, panelView, ggplot2, and others from CRAN. It also installs the latest 'fect' package from GitHub and a compatible 'HonestDiDFEct' fork. ```R packages <- c("dplyr", "fixest", "did", "didimputation", "panelView", "ggplot2", "bacondecomp", "HonestDiD", "DIDmultiplegtDYN", "PanelMatch") install.packages(setdiff(packages, rownames(installed.packages()))) if ("fect" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("xuyiqing/fect") } if ("HonestDiDFEct" %in% rownames(installed.packages()) == FALSE) { devtools::install_github("lzy318/HonestDiDFEct") } ``` -------------------------------- ### Display Simulated Data Head Source: https://yiqingxu.org/packages/fect/04-gsynth Displays the first few rows of the 'simgsynth' dataset, which is used for demonstrating the Gsynth method. This helps in understanding the data structure. ```R head(simgsynth) ``` -------------------------------- ### fect Package Lifecycle and Dependencies Source: https://yiqingxu.org/packages/fect/index Information regarding the lifecycle status of the fect package and its dependencies. It indicates that fect is currently 'experimental' and lists 'gsynth' as a retiring dependency. ```APIDOC fect Package Status: - Lifecycle: Experimental (https://www.tidyverse.org/lifecycle/#experimental) - License: MIT (https://opensource.org/licenses/MIT) - CRAN Index: https://cran.r-project.org/web/packages/fect/index.html gsynth Package Status: - CRAN Index: https://cran.r-project.org/web/packages/gsynth/index.html - Status: Retiring ``` -------------------------------- ### Sensitivity Analysis Setup and Execution Source: https://yiqingxu.org/packages/fect/06-sens Prepares parameters for sensitivity analysis using `fect_sens` and then executes the function. This involves defining post-treatment periods and specifying parameters for Relative Magnitude (RM) and Smoothness restrictions, which are used to assess the robustness of the estimated dynamic treatment effects. ```R # Define post-treatment periods and sensitivity parameters for fect_sens T.post <- 10 # Number of post-treatment periods based on original analysis post_periods_vec <- 1:T.post # Parameters for Relative Magnitude (RM) restriction Mbar_vec_avg_rm <- seq(0, 1, by = 0.1) # For average ATT plot Mbar_vec_period_rm <- c(0, 0.5) # For period-by-period ATT plot # Parameters for Smoothness restriction M_vec_avg_smooth <- seq(0, 0.25, by = 0.05) # For average ATT plot M_vec_period_smooth <- c(0, 0.1) # For period-by-period ATT plot # Run sensitivity analysis using fect_sens # This function augments out.fect.placebo with sensitivity results ``` -------------------------------- ### Estimating Gsynth with Matrix Completion Source: https://yiqingxu.org/packages/fect/04-gsynth Estimates the Gsynth model using the matrix completion method on an unbalanced panel. Includes parameters for minimum pre-treatment time, data, index variables, method, standard errors, and bootstrapping. ```R out.mc_ub <- fect(turnout ~ policy_edr + policy_mail_in + policy_motor, min.T0 = 8, data = turnout.ub, index = c("abb","year"), method = "mc", se = TRUE, nboots = 1000, seed = 02139) ``` -------------------------------- ### MC Method with Parameter Tuning Source: https://yiqingxu.org/packages/fect/02-fect Demonstrates the usage of the 'mc' method in the fect package for matrix completion, including specifying candidate tuning parameters (lambda) and cross-validation. It also shows how to plot the results. ```R out.mc <- fect(Y ~ D + X1 + X2, data = simdata, index = c("id","time"), force = "two-way", method = "mc", CV = TRUE, se = TRUE, nboots = 200, parallel = TRUE) plot(out.mc, main = "Estimated ATT (MC)") ``` -------------------------------- ### IFE and MC Estimation with Placebo Test Source: https://yiqingxu.org/packages/fect/02-fect Demonstrates how to perform IFE and MC estimations using the fect function, including setting up the model, specifying the data, and enabling parallel processing and standard error calculations. It also shows how to conduct placebo tests with bootstrapping. ```R out.ife.p <- fect(Y ~ D + X1 + X2, data = simdata, index = c("id", "time"), force = "two-way", method = "ife", r = 2, CV = 0, parallel = TRUE, se = TRUE, nboots = 200, placeboTest = TRUE, placebo.period = c(-2, 0)) ``` ```R out.mc.p <- fect(Y ~ D + X1 + X2, data = simdata, index = c("id", "time"), force = "two-way", method = "mc", lambda = out.mc$lambda.cv, CV = 0, parallel = TRUE, se = TRUE, nboots = 200, placeboTest = TRUE, placebo.period = c(-2, 0)) ``` -------------------------------- ### fect Methods Overview Source: https://yiqingxu.org/packages/fect/07-cheetsheet Lists the available methods in the 'fect' package for estimating treatment effects, along with their corresponding models for $\hat{Y}(0)$ and key references. ```R fect(methods = "___") | Method | Model for $\hat{Y}(0)$ | References | |------------|--------------------------------|--------------------------------------------------| | fe | Standard two-way fixed effects | Liu, Wang & Xu (2022), Borusyak, Jaravel & Spiess (2024) | | ife | Interactive fixed effects | Gobillon & Magnac (2016), Xu (2017) | | mc | Matrix completion | Athey et al. (2021) | | polynomial | Two-way fixed effects with unit-specific trends | – | | cfe | "Complex" or multi-level fixed effects | – | | gsynth | Interactive fixed effects | Xu (2017) | ```