I need some help troubleshooting this code. I want to include spline terms using the bs() function in my WeightIt propensity score model but I am getting the following error: Error in terms.formula(new.form) : invalid model formula in ExtractVars
This code worked a couple of weeks ago, but now throws an error. WeightIt has not been updated recently so I am having a hard time understanding what has changed.
Thanks!
require(WeightIt)
#> Loading required package: WeightIt**strong text**
weightit(weight ~ bs(height), data = women, estimand="ATE", method="ps", stabilize=T, include.obj = T)
#> Error: All variables in formula must be variables in data or objects in the global environment.
#> Missing variables: bs(height)
Thanks for your response. bs() is a base function that is supposed to create spline and include spline terms in your model. So yes, height works, but it does not include spline terms for height in my model.
You can use the following hack to get around this:
library(WeightIt)
library(splines)
library(magrittr)
# do the basis expansion ahead of time. this creates a
# data.frame with a matrix column, which we need to expand
women2 <- model.frame(weight ~ bs(height), women)
# not sure the best way to flatten the matrix column into vector columns
# so this is an ugly hack. there's probably a better way to do this
# with recipes.
women3 <- as.data.frame(apply(women2, 2, as.vector)) %>%
set_names(c("weight", "b1", "b2", "b3"))
weightit(
weight ~ b1 + b2 + b3,
data = women3,
estimand = "ATE",
method = "ps",
stabilize = TRUE,
include.obj = TRUE
)
#> A weightit object
#> - method: "ps" (propensity score weighting)
#> - number of obs.: 15
#> - sampling weights: none
#> - treatment: continuous
#> - covariates: b1, b2, b3