jkcshea / ivmte

An R package for implementing the method in Mogstad, Santos, and Torgovitsky (2018, Econometrica).
GNU General Public License v3.0
18 stars 2 forks source link

Factor variable error when constructing small intial grid #219

Closed jkcshea closed 2 years ago

jkcshea commented 2 years ago

The following specification generates an error.

dtcf <- ivmte:::gendistCovariates()$data.full
result <- ivmte(data = dtcf,
                outcome = "ey",
                propensity = p,
                m0 = ~ x1 + x1:uSplines(degree = 0, knots = c(1/3, 2/3)) +
                    factor(x2):uSplines(degree = 0, knots = c(1/3, 2/3)),
                m1 = ~ x1 + x1:uSplines(degree = 0, knots = c(1/3, 2/3)) +
                    factor(x2):uSplines(degree = 0, knots = c(1/3, 2/3)),
                target = "genlate",
                genlate.lb = 0.2,
                genlate.ub = 0.7,
                treat = d,
                initgrid.nx = 1)

Here is the output.

Obtaining propensity scores...

Generating target moments...
    Integrating terms for control group...
    Integrating terms for treated group...

Performing direct MTR regression...
    MTR is not point identified.

Performing audit procedure...
    Solver: Gurobi ('gurobi')
    Generating initial constraint grid...

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels

This is because of the following: The initial grid is a design matrix constructed using a random sample from the support of the covariates. In this example, you sampled only one value of x2. However, the MTR formulas involve the term factor(x2). So R throws an error since it is expecting at least 2 values of x2.

This can be corrected by checking the support of factor variables when constructing the initial grid, and adjusting the MTR formulas as necessary. This is actually done in mst.R:

https://github.com/jkcshea/ivmte/blob/7c67a265deb70e735f2b521ebc1733c8af822cf3/R/mst.R#L2090-L2106

jkcshea commented 2 years ago

Fixed!