if (FALSE) { # requireNamespace("lmtest", quietly = TRUE)
set.seed(123, "L'Ecuyer-CMRG")
data("infert")
fit <- glm(case ~ spontaneous + induced, data = infert,
family = "binomial")
lmtest::coeftest(fit, vcov. = vcovFWB, R = 200)
}
if (FALSE) { # requireNamespace("sandwich", quietly = TRUE)
# Example from help("vcovBS", package = "sandwich")
data("PetersenCL", package = "sandwich")
m <- lm(y ~ x, data = PetersenCL)
# Note: this is not to compare performance, just to
# demonstrate the syntax
cbind(
"BS" = sqrt(diag(sandwich::vcovBS(m))),
"FWB" = sqrt(diag(vcovFWB(m))),
"BS-cluster" = sqrt(diag(sandwich::vcovBS(m, cluster = ~firm))),
"FWB-cluster" = sqrt(diag(vcovFWB(m, cluster = ~firm)))
)
# Using `wtype = "multinom"` exactly reproduces
# `sandwich::vcovBS()`
set.seed(11)
s <- sandwich::vcovBS(m, R = 200)
set.seed(11)
f <- vcovFWB(m, R = 200, wtype = "multinom")
all.equal(s, f)
}
# Using a custom argument to `.coef`
set.seed(123)
data("infert")
fit <- nnet::multinom(education ~ age, data = infert,
trace = FALSE)
# vcovFWB(fit, R = 200) ## error
coef(fit) # coef() returns a matrix
# Write a custom function to extract vector of
# coefficients (can also use marginaleffects::get_coef())
coef_multinom <- function(x) {
p <- t(coef(x))
setNames(as.vector(p),
paste(colnames(p)[col(p)],
rownames(p)[row(p)],
sep = ":"))
}
coef_multinom(fit) # returns a vector
vcovFWB(fit, R = 200, .coef = coef_multinom)
Run the code above in your browser using DataLab