課後自由探索:輔助檢證R套件{interflex}

面對這個非常新的且有重要價值的研究工具,老師非常期待有心的同學努力登上世界舞台的前緣。

User’s Guide – interflex

An R package that produces "flexible" marginal effect estimates with multiplicative interaction models

Reference: How Much Should We Trust Estimates from Multiplicative Interaction Models? Simple Tools to Improve Empirical Practice

Authors: Jens Hainmueller (Stanford); Jonathan Mummolo (Stanford); Yiqing Xu (UCSD)

Maintainer: Yiqing Xu [yiqingxu@ucsd.edu]

Date: March 5, 2017

Version: 1.0.3.

Changes in this version: CRAN Version.

Changes in Version 1.0.2: (1) Fix bugs; (2) Integrate the Wald test into inter.binning; (3) Complete R help files; (4) Updated fast fixed effects algorithm.

Changes in Version 1.0.1: (1) Enhanced speed (with C++ code embedded); (2) Support linear fixed effect models; (3) Improved cross-validation procedure; (4) Improved visualization.

R source files can be found on Github. R code appearing in this demonstration can be downloaded from here.

Comments and suggestions will be greatly appreciated!


Contents

  1. Installation
  2. Load package and toy examples
  3. Raw plots (and GAM plots)
  4. Binning estimates
  5. Kernel estimates
  6. Fixed effects

Installation

You can install the interflex package from CRAN:

install.packages('interflex', type = "source", repos = 'http://cran.us.r-project.org') 

Or you can install the up-to-date development version from Github:

install.packages('devtools', repos = 'http://cran.us.r-project.org') # if not already installed
library(devtools)
install_github('xuyiqing/interflex')

interflex depends on the following packages, which will be installed AUTOMATICALLY when interflex is being installed; if not, please install them manually:

require(Rcpp) # for processing C++ code
require(ggplot2)  # for plotting
require(plotrix) # for plotting
require(mgcv) # for GAM
require(pcse) # in case panel-corrected standard errors will be used
require(foreach)  # for parallel computing in kernel estimation
require(doParallel) # for parallel computing in kernel estimation
require(lmtest) # for wald test
require(Lmoments) # for L-kurtosis measure

Mac users who encounter "-lgfortran" or "-lquadmath" error during installation, please check out the solution here. Typing the following two lines of code in your Terminal should solve this problem.

curl -O http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2
sudo tar fvxz gfortran-4.8.2-darwin13.tar.bz2 -C /

Load Package and Toy Examples

Now let’s load the package as well as four simulated toy datasets:

library(interflex)
data(interflex)
ls()
## [1] "s1" "s2" "s3" "s4"

s1 is a case of dichotomous treatment indicator with linear marginal effects; s2 is a case of continuous treatment indicator with linear marginal effects; s3 is a case of dichotomous treatment indicator with nonlinear marginal effects; and s4 is a case of dichotomous treatment indicator, nonlinear marginal effects, with additive two-way fixed effects. They are generated using the following code.

set.seed(1234)
n<-200
d1<-sample(c(0,1),n,replace=TRUE) # dichotomous treatment
d2<-rnorm(n,3,1) # continuous treatment
x<-rnorm(n,3,1) # moderator
z<-rnorm(n,3,1) # covariate
e<-rnorm(n,0,1) # error term

## linear marginal effect
y1<-5 - 4 * x - 9 * d1 + 3 * x * d1 + 1 * z + 2 * e
y2<-5 - 4 * x - 9 * d2 + 3 * x * d2 + 1 * z + 2 * e
s1<-cbind.data.frame(Y = y1, D = d1, X = x, Z1 = z)
s2<-cbind.data.frame(Y = y2, D = d2, X = x, Z1 = z)

## quadratic marginal effect
x3 <- runif(n, -3,3) # uniformly distributed moderator
y3 <- d1*(x3^2-2.5) + (1-d1)*(-1*x3^2+2.5) + 1 * z + 2 * e
s3 <- cbind.data.frame(D=d1, X=x3, Y=y3, Z1 = z)

## adding two-way fixed effects
n  <- 500
d4 <-sample(c(0,1),n,replace=TRUE) # dichotomous treatment
x4 <- runif(n, -3,3) # uniformly distributed moderator
z4 <- rnorm(n, 3,1) # covariate
alpha <- 20 * rep(rnorm(n/10), each = 10)
xi <- rep(rnorm(10), n/10)
y4 <- d4*(x4^2-2.5) + (1-d4)*(-1*x4^2+2.5) + 1 * z4 + alpha + xi + 2 * rnorm(n,0,1)
s4 <- cbind.data.frame(D=d4, X=x4, Y=y4, Z1 = z4, unit = rep(1:(n/10), each = 10), year = rep(1:10, (n/10)))

The implied population marginal effects for the DGPs of s1 and s2 are

ME(X)=3X9;ME(X)=3X9;
the implied population marginal effects for the DGPs of s3 and s4 are
ME(X)=2X25.ME(X)=2X25.

The interflex package ships four functions: inter.raw, inter.gam, inter.binning, and inter.kernel, which we will explain in detail below.


Raw Plots

The first step of the diagnostics is to plot raw data. We supply the function inter.raw with the variable names of the outcome Y, the treatment D, and the moderator X. You can also supply labels for these variables. If you supply a variable name to the weights option, the linear and LOESS fits will be adjusted based on the weights. Note that the correlations between covariates Z and Y are NOT partialed out.

inter.raw(Y = "Y", D = "D", X = "X", data = s1, weights = NULL, Ylabel = "Outcome", Dlabel = "Treatment", Xlabel="Moderator")

inter.raw(Y = "Y", D = "D", X = "X", data = s2, Ylabel = "Outcome", Dlabel = "Treatment", Xlabel="Moderator")

inter.raw(Y = "Y", D = "D", X = "X", data = s3, Ylabel = "Outcome", Dlabel = "Treatment", Xlabel="Moderator")

For the continuous treatment case (e.g. s2), we can also draw a Generalized Additive Model (GAM) plot. You can supply a set of covariates to be controlled for by supplying Z, which takes a vector of covariate names (strings).

inter.gam(Y="Y", D="D", X="X", Z=c("Z1"), data=s2)


Binning Estimates

The second diagnostic tool is the binning plot. The nbins option sets the number of bins. The default number of bins is 3, and equal-sized bins are created based on the distribution of the moderator. There are four options for the choice of the variance estimator: vartype="homoscedastic", "robust", "cluster", and "pcse". The default option is "homoscedastic".

Note that inter.binning will also automatically report a set of statistics, including: (1) the binning estimates and their standard errors and 95% confidence intervals, (2) the percentage of observations within each bin, (3) the variance of the treatment within each bin, (4) the L-kurtosis of the moderator, (5) whether the three binning estimates are in the correct order (i.e. monotonically increasing or decreasing), (6) pair-wise t-statistics for the binning estimates (when there are 2 or 3 bins), and (7) a Wald test to formally test if we can reject the linear multiplicative interaction model by comparing it with a more flexible model of multiple bins.

inter.binning(Y = "Y", D = "D", X = "X", Z = "Z1", data = s1, vartype = "robust")
## $est.binning
##                      x0    coef     se CI_lower CI_upper
## X: [-0.396,2.48] 2.0467 -3.0545 0.5001  -4.0411  -2.0679
## X: (2.48,3.42]   2.9599  0.5706 0.4823  -0.3808   1.5220
## X: (3.42,6.2]    4.1025  3.1651 0.4770   2.2242   4.1061
## 
## $binary.treatment
## [1] 1
## 
## $bin.size
##     1     2     3 
## 0.335 0.330 0.335 
## 
## $treat.variation.byGroup
## [1] 1.0459 1.2955 0.9281
## 
## $X.Lkurtosis
## [1] 0.1241
## 
## $correctOrder
## [1] TRUE
## 
## $p.twosided
## p.1v2 p.2v3 p.1v3 
## 0e+00 2e-04 0e+00 
## 
## $p.wald
## [1] 0.5054
## 
## $graph

We see that the Wald test cannot reject the NULL hypothesis that the linear interaction model and the three-bin model are statistically equivalent (p = 0.51).

The binning estimates for the continuous case are shown below (we now present the distribution of the moderator with a density plot using option Xdist = "density" – the default option is "hist" or "histogram"):

inter.binning(Y = "Y", D = "D", X = "X", Z = "Z1", data = s2, Xdistr = "density")

Note that you can customize the cutoff values for the bins, for example, set cutoffs = c(1, 2, 4, 5) to create five bins: [minX, 1], (1, 2], (2,4], (4, 5] and (5,maxX] (supplying N numbers will create N+1 bins). Note that the cutoffs option will override the nbins option if they are incompatible.

inter.binning(Y = "Y", D = "D", X = "X", Z = "Z1", data = s2, cutoffs = c(1,2,4,5))

The binning estimates for the dichotomous, nonlinear case (i.e. s3) are shown below. A linear interaction model clearly gives misleading marginal effects estimates. The marginal effects plot is stored in out$graph while the estimates and standard errors are stored in out$est.

inter.binning(Y = "Y", D = "D", X = "X", Z = "Z1", data = s3)
## $est.binning
##                       x0    coef     se CI_lower CI_upper
## X: [-2.99,-1.02] -2.0404  3.9497 0.4668   3.0288   4.8705
## X: (-1.02,1]      0.1642 -3.7860 0.4967  -4.7658  -2.8061
## X: (1,2.96]       1.8977  3.0686 0.4722   2.1370   4.0001
## 
## $binary.treatment
## [1] 1
## 
## $bin.size
##     1     2     3 
## 0.335 0.330 0.335 
## 
## $treat.variation.byGroup
## [1] 1.0459 1.0154 1.1789
## 
## $X.Lkurtosis
## [1] -0.0019
## 
## $correctOrder
## [1] FALSE
## 
## $p.twosided
##  p.1v2  p.2v3  p.1v3 
## 0.0000 0.0000 0.1862 
## 
## $p.wald
## [1] 0
## 
## $graph

This time the NULL hypothesis that the linear interaction model and the three-bin model are statistically equivalent is safely rejected (p.wald = 0.00).


Kernel Estimates

With the kernel method, a bandwidth is first selected via 5-fold least-squares cross-validation. The standard errors are produced by a non-parametric bootstrap (you can adjust the number of bootstrap iterations using the nboots option). The grid option can either be an interger, which specifies the number of bandwidths to be cross-validated, or a vector of candidate bandwidths – the default is grid = 20. You can also specify a clustered group structure by using the cl option, in which case a block bootstrap procedure will be performed.

Even with an optimized algorithm, the bootstrap procedure for large datasets can be slow. We incorporate parallel computing (parallel=TRUE) to speed it up. You can choose the number of cores to be used for parallel computing; otherwise the program will detect the number of logical cores in your computer and use as many cores as possible (warning: this will significantly slow down your computer!):

inter.kernel(Y = "Y", D = "D", X = "X", Z="Z1", data = s1, nboots = 200, parallel = TRUE, cores = 4)

If you specify a bandwidth manually (for example, by setting bw=1.3), the cross-validation step will be skipped. The main option controls the title of the plot while the xlim and ylim options control the ranges of the x-axis and y-axis, respectively.

inter.kernel(Y = "Y", D = "D", X = "X", Z = "Z1", data = s2, nboots = 200, bw = 1.3, main = "Title", xlim = c(-2,8), ylim = c(-15, 15))

The kernel method produces non-linear marginal effects estimates that are much closer to the effects implied by the true DGP.

inter.kernel(Y = "Y", D = "D", X = "X", Z = "Z1", data = s3)


Fixed Effects

Finally, we move on to linear fixed effects models. Remember in s4, a large chunck of the variation in the outcome variable is driven by group fixed effects. Below is a scatterplot of the raw data (group index vs. outcome). Red and green dots represent treatment and control units, respectively. We can see that outcomes are highly correlated within a group.

ggplot(s4, aes(x=group, y = Y, colour = as.factor(D))) + geom_point() + guides(colour=FALSE) 

When fixed effects are present, it is possible that we cannot observe a clear pattern of marginal effects in the raw plot as before, while binning estimates have wide confidence intervals:

inter.raw(Y = "Y", D = "D", X = "X", data = s4, weights = NULL)

inter.binning(Y = "Y", D = "D", X = "X", Z = "Z1", data = s4, FE = NULL, cl = "group")

The binning estimates are much more informative when fixed effects are included, by using the FE option. Note that the number of group indicators can exceed 2. Our algorithm is optimized for a large number of fixed effects or many group indicators. The cl option controls the level at which standard errors are clustered.

s4$wgt <- 1
inter.binning(Y = "Y", D = "D", X = "X", Z = "Z1", data = s4, FE = c("group","year"), cl = "group", weights = "wgt")

When fixed effects are not taken into account, the kernel estimates are also less precisely estimated. Because the model is incorrectly specified, cross-validated bandwidths also tend to be bigger than optimal.

inter.kernel(Y = "Y", D = "D", X = "X", Z = "Z1", data = s4, FE = NULL, cl = "group", weights = "wgt")

Controlling for fixed effects by using the FE option solves this problem. The estimates are now much closer to the population truth. Note that, with inter.kernel, all uncertainty estimates are produced via bootstrapping. When the cl option is specified, a block bootstrap procedure will be performed.

inter.kernel(Y = "Y", D = "D", X = "X", Z = "Z1", data = s4, FE = c("group","year"), cl = "group")

With large datasets, cross-validation or bootstrapping can take a while. One way to check the result quickly is to shut down the bootstrap procedure (using CI = FALSE). inter.kernel will then present the point estimates only. Another way is to supply a reasonable bandwidth manually by using the bw option such that cross-validation will be skipped.

inter.kernel(Y = "Y", D = "D", X = "X", Z = "Z1", data = s4, bw = 0.62, FE = c("group","year"), cl = "group", CI = FALSE, ylim = c(-9, 15))