# NOT RUN {
library("cobalt")
data("lalonde", package = "cobalt")
#A user-defined version of method = "ps"
my.ps <- function(treat, covs, estimand, focal = NULL) {
covs <- make.full.rank(covs)
d <- data.frame(treat, covs)
f <- formula(d)
ps <- glm(f, data = d, family = "binomial")$fitted
if (estimand == "ATT") w <- ifelse(treat == focal, 1, ps/(1-ps))
else if (estimand == "ATE") w <- ifelse(treat == 1, 1/ps, 1/(1-ps))
return(list(w = w, ps = ps))
}
#Balancing covariates between treatment groups (binary)
(W1 <- weightit(treat ~ age + educ + married +
nodegree + re74, data = lalonde,
method = my.ps, estimand = "ATT"))
summary(W1)
bal.tab(W1)
#Balancing covariates for logitdinal treatments
# my.ps is used at each time point.
library("twang")
data("iptwExWide", package = "twang")
(W2 <- weightitMSM(list(tx1 ~ age + gender + use0,
tx2 ~ tx1 + use1 + age + gender + use0,
tx3 ~ tx2 + use2 + tx1 + use1 + age + gender + use0),
data = iptwExWide,
method = my.ps))
summary(W2)
bal.tab(W2)
# Kernel balancing using the KBAL package, available
# using devtools::install_github("chadhazlett/KBAL").
# Only the ATT and ATC are available. Use 'kbal.method'
# instead of 'method' in weightit() to choose between
# "ebal" and "el".
kbal.fun <- function(treat, covs, estimand, focal, ...) {
args <- list(...)
if (is_not_null(focal))
treat <- as.numeric(treat == focal)
else if (estimand != "ATT")
stop("estimand must be 'ATT' or 'ATC'.", call. = FALSE)
if ("kbal.method" %in% names(args)) {
names(args)[names(args) == "kbal.method"] <- "method"
}
args[names(args) %nin% setdiff(names(formals(KBAL::kbal)),
c("X", "D"))] <- NULL
k.out <- do.call(KBAL::kbal, c(list(X = covs, D = treat),
args))
w <- k.out$w
return(list(w = w))
}
(Wk <- weightit(treat ~ age + educ + married +
nodegree + re74, data = lalonde,
method = kbal.fun, estimand = "ATT"))
summary(Wk)
bal.tab(Wk, disp.ks = TRUE)
# }
Run the code above in your browser using DataLab