no native code · R: 67 definitions, 6 typed strict, 38 gradual, prelude debt 35 · fuzzing: 4 definitions, 0 unsound, 4 accept calls outside their domain · tyr dc7f1a7 · Rsem 5c142d7 · NativeSem 770a1eb · rstt 2b2696f unpinned
Invalid_argument("Variable ..._5 is already bound.")nobs0 <- function(x, ...) {
nobs1 <- if("stats4" %in% loadedNamespaces()) stats4::nobs else stats::nobs
nobs2 <- function(x, ...) NROW(residuals(x, ...))
rval <- try(nobs1(x, ...), silent = TRUE)
if(inherits(rval, "try-error") | is.null(rval)) rval <- nobs2(x, ...)
return(rval)
}vcov — a name the prelude does not declarename: vcov
vcov0 <- if(!is.null(vcov)) vcov else {
if("stats4" %in% loadedNamespaces()) stats4::vcov else stats::vcov
}ifelse — a name the prelude does not declarename: ifelse
kweights <- function(x, kernel = c("Truncated", "Bartlett", "Parzen",
"Tukey-Hanning", "Quadratic Spectral"), normalize = FALSE)
{
kernel <- match.arg(kernel,
c("Truncated", "Bartlett", "Parzen", "Tukey-Hanning", "Quadratic Spectral"))
if(normalize) {
ca <- switch(kernel,
"Truncated" = 2,
"Bartlett" = 2/3,
"Parzen" = .539285,
"Tukey-Hanning" = 3/4,
"Quadratic Spectral" = 1)
} else {
ca <- 1
}
switch(kernel,
"Truncated" = {
ifelse(ca * abs(x) > 1, 0, 1)
},
"Bartlett" = {
ifelse(ca * abs(x) > 1, 0, 1 - abs(ca * x))
},
"Parzen" = {
ifelse(ca * abs(x) > 1, 0, ifelse(ca * abs(x) < 0.5,
1 - 6 * (ca * x)^2 + 6 * abs(ca * x)^3,
2 * (1 - abs(ca * x))^3))
},
"Tukey-Hanning" = {
ifelse(ca * abs(x) > 1, 0, (1 + cos(pi * ca * x))/2)
},
"Quadratic Spectral" = {
qs <- function(x) {
y <- 6 * pi * x/5
3 * (1/y)^2 * (sin(y)/y - cos(y))
}
w <- qs(x)
if(length(ix <- which(abs(x) < 1e-3)) > 0L) {
cf <- 1e6 * log(qs(1e-3))
w[ix] <- exp(cf * x[ix]^2)
}
w
}
)
}argument: @(DBL | 'w, 1.<> | 'I887 & (CHR | DBL | INT | LGL | RAW)) failing call: base::[](NA_real_, as.raw(0))
pava.blocks <- function(x, w = rep(1, length(x)),
b = rep(1, length(x)), up = TRUE)
{
lasti <- 1
if(length(x) == 1) rval <- list(x = x, blocks = b,increasing = up)
else {
for(i in 2:length(x)) {
if(x[i] <= x[lasti] & up){
wtotal <- w[lasti]+w[i]
x[lasti] <- (x[lasti]*w[lasti]+x[i]*w[i])/wtotal
w[lasti] <- wtotal
b[lasti] <- b[i]+b[lasti]
b[i] <- 0
} else if(x[i] <= x[lasti] & !up) {
lasti <- i
} else if(x[i] > x[lasti] & !up) {
wtotal <- w[lasti]+w[i]
x[lasti] <- (x[lasti]*w[lasti]+x[i]*w[i])/wtotal
w[lasti] <- wtotal
b[lasti] <- b[i]+b[lasti]
b[i] <- 0
} else if(x[i] > x[lasti] & up) {
lasti <- i
}
}
if(any(b == 0)) {
subset <- (b > 0)
rval <- pava.blocks(x[subset],w[subset],b[subset],up)
} else
rval <- list(x = x,blocks = b,increasing = up)
}
return(rval)
}sqrt — a name the prelude does not declarename: sqrt
isoacf <- function(x, lagmax = NULL, weave1 = FALSE)
{
acfWeave <- function(x, lag = trunc(5*sqrt(length(x))))
{
x <- x - mean(x)
# n <- length(x)
autocov <- function(ii, xx)
cov(xx[1:(length(xx)-ii+1)],xx[ii:length(xx)])
covs <- sapply(2:lag, autocov, xx = x)
covs/var(x)
}
if(weave1) {
lagmax <- trunc(5*sqrt(length(x)))
lagmax <- min(length(x) - 1, lagmax)
covs <- acfWeave(x, lag = lagmax)
isocovs <- pava.blocks(c(covs,0), c((length(x)-1):(length(x)-length(covs)),
.Machine$double.xmax), up = FALSE)
rval <- c(1, rep(isocovs$x, isocovs$blocks))
} else {
lagmax <- length(x) - 1
lagmax <- min(length(x) - 1, lagmax)
covs <- as.vector(acf(x, lag.max = lagmax -1, plot = FALSE)$acf)[-1]
rval <- c(1, -isoreg(1:(length(covs)+1), c(-covs, 0))$yf)
}
return(rval)
}UseMethod — a name the prelude does not declarename: UseMethod
bread <- function(x, ...)
{
UseMethod("bread")
}nobs0 — one of the package’s own names, itself untypedname: nobs0
bread.default <- function(x, ...) {
nobs0(x) * vcov0(x, ...)
}summary.lm — a name the prelude does not declarename: summary.lm
bread.lm <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
sx <- summary.lm(x)
return(sx$cov.unscaled * as.vector(sum(sx$df[1L:2L])))
}coef — a name the prelude does not declarename: coef
bread.mlm <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
cf <- coef(x)
rval <- summary.lm(x)
rval <- kronecker(
structure(diag(ncol(cf)), dimnames = rep.int(list(colnames(cf)), 2L)),
structure(rval$cov.unscaled, dimnames = rep.int(list(rownames(cf)), 2L)) * as.vector(sum(rval$df[1L:2L])),
make.dimnames = TRUE
)
return(rval)
}summary — a name the prelude does not declarename: summary
bread.glm <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
sx <- summary(x)
wres <- as.vector(residuals(x, "working")) * weights(x, "working")
dispersion <- if(substr(x$family$family, 1L, 17L) %in% c("poisson", "binomial", "Negative Binomial")) 1
else sum(wres^2)/sum(weights(x, "working"))
return(sx$cov.unscaled * as.vector(sum(sx$df[1L:2L])) * dispersion)
}summary — a name the prelude does not declarename: summary
bread.nls <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
sx <- summary(x)
return(sx$cov.unscaled * as.vector(sum(sx$df[1L:2L])))
}vcov — a name the prelude does not declarename: vcov
bread.polr <- function(x, ...)
{
vcov(x) * x$n
}vcov — a name the prelude does not declarename: vcov
bread.clm <- function(x, ...)
{
vcov(x) * x$n
}(((x: { naive.var: (INT | dbl & v('I1283))<. | `I113>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: (INT | dbl & v('I1283))<. | `I113>, any }, ...: any) -> (INT | (DBL | INT) & v('I1283))<. | `I113>) & ((x: { naive.var: DBL1<. | `I113>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: DBL1<. | `I113>, any }, ...: any) -> DBL1<. | `I113>) & ((x: { naive.var: dbl1<. | `I113>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: dbl1<. | `I113>, any }, ...: any) -> dbl1<. | `I113>))<>| parameter | change | call | returned |
|---|---|---|---|
| x | kind:env | bread.survreg(new.env(), function(...) local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), character(0)) | (INT & ~vec1)<> with { } |
| x | unwrap | bread.survreg(list(), "fuzz_dot1" = NULL) | (INT & ~vec1)<> with { } |
| x | wrap | bread.survreg("x" = list(list("linear.predictors" = NULL, "naive.var" = NULL, "var" = -2147483647L, quote(f(x)))), "fuzz_dot1" = c(NA_complex_, complex(real = 0, imaginary = 0)), "fuzz_dot2" = list(new.env(), as.name("x"))) | (INT & ~vec1)<> with { } |
| call | verdict | error |
|---|---|---|
| bread.survreg(list("linear.predictors" = local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), "naive.var" = as.raw(c(255)), as.name("x"), NULL), list(function(...) c(NA, NA), quote(f(x))), as.raw(c(0)), "fuzz_dot1" = function(...) new.env()) | error_type | base::*: non-numeric argument to binary operator |
| bread.survreg(list("linear.predictors" = new.env(), "naive.var" = as.raw(c(0)), new.env(), NULL), "fuzz_dot1" = function(...) NULL, "fuzz_dot2" = local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p })) | error_type | base::*: non-numeric argument to binary operator |
| bread.survreg(list("linear.predictors" = NULL, "naive.var" = NULL, "var" = as.raw(c(255))), "fuzz_dot1" = NULL, "fuzz_dot2" = new.env()) | error_type | base::*: non-numeric argument to binary operator |
| bread.survreg(list("linear.predictors" = NULL, "naive.var" = NULL, "var" = as.raw(c(255)))) | error_type | base::*: non-numeric argument to binary operator |
bread.survreg <- function(x, ...)
length(x$linear.predictors) * if(is.null(x$naive.var)) x$var else x$naive.varsummary — a name the prelude does not declarename: summary
bread.gam <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
sx <- summary(x)
sx$cov.unscaled * sx$n
}coef — a name the prelude does not declarename: coef
bread.coxph <- function(x, ...)
{
rval <- x$n * if(is.null(x$naive.var)) x$var else x$naive.var
dimnames(rval) <- list(names(coef(x)), names(coef(x)))
return(rval)
}(((x: { n: (dbl & v('I1403))<`I122>, vcov: (dbl & v('I1403))<@"*", `I122>, any }, ...: any) -> (INT | (DBL | INT) & v('I1403))<`I122>) & ((x: { n: DBL1<`I122>, vcov: dbl1<@"*", `I122>, any }, ...: any) | (x: { n: dbl1<`I122>, vcov: DBL1<@"*", `I122>, any }, ...: any) -> DBL1<`I122>) & ((x: { n: any, vcov: <@"*", ...>, any }, ...: any) -> (DBL | INT)<difftime> | LGL<>) & ((x: { n: dbl1<`I122>, vcov: dbl1<@"*", `I122>, any }, ...: any) -> dbl1<`I122>))<>| parameter | change | call | returned |
|---|---|---|---|
| x | drop | bread.hurdle(new.env()) | (INT & ~vec1)<> with { } |
| x | kind:lang | bread.hurdle(quote(f(x)), as.name("x"), "fuzz_dot1" = NULL) | (INT & ~vec1)<> with { } |
| x | wrap | bread.hurdle(list(list("n" = FALSE, "vcov" = TRUE, NA))) | (INT & ~vec1)<> with { } |
| call | verdict | error |
|---|---|---|
| bread.hurdle(list("n" = as.raw(c(0)), "vcov" = as.raw(c(0, 255)), as.name("x"), list()), as.name("x"), as.name("x"), "fuzz_dot1" = as.name("x")) | error_type | base::*: non-numeric argument to binary operator |
| bread.hurdle("x" = list("n" = as.raw(c(0, 0)), "vcov" = as.raw(c(0))), "fuzz_dot1" = NULL) | error_type | base::*: non-numeric argument to binary operator |
| bread.hurdle(list("n" = as.raw(c(0)), "vcov" = 0.5, local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), list(list(quote(f(x))), as.name("x"))), as.name("x"), "fuzz_dot1" = NULL) | error_type | base::*: non-numeric argument to binary operator |
| bread.hurdle(list("n" = as.raw(c(0)), "vcov" = as.raw(c(0)), quote(f(x)), as.name("x")), quote(f(x)), list()) | error_type | base::*: non-numeric argument to binary operator |
| bread.hurdle("x" = list("n" = FALSE, "vcov" = as.raw(c(0))), "fuzz_dot1" = new.env()) | error_type | base::*: non-numeric argument to binary operator |
bread.hurdle <- function(x, ...)
{
x$vcov * x$n
}(((x: { n: (dbl & v('I1422))<`I126>, vcov: (dbl & v('I1422))<@"*", `I126>, any }, ...: any) -> (INT | (DBL | INT) & v('I1422))<`I126>) & ((x: { n: DBL1<`I126>, vcov: dbl1<@"*", `I126>, any }, ...: any) | (x: { n: dbl1<`I126>, vcov: DBL1<@"*", `I126>, any }, ...: any) -> DBL1<`I126>) & ((x: { n: any, vcov: <@"*", ...>, any }, ...: any) -> (DBL | INT)<difftime> | LGL<>) & ((x: { n: dbl1<`I126>, vcov: dbl1<@"*", `I126>, any }, ...: any) -> dbl1<`I126>))<>| parameter | change | call | returned |
|---|---|---|---|
| x | kind:null | bread.zeroinfl("x" = NULL) | (INT & ~vec1)<> with { } |
| x | kind:null | bread.zeroinfl(NULL, local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), new.env(), "fuzz_dot1" = quote(f(x)), "fuzz_dot2" = NULL) | (INT & ~vec1)<> with { } |
| x | wrap | bread.zeroinfl(list(list("n" = as.raw(c(0, 255, 0, 255, 0)), "vcov" = raw(0), local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p })))) | (INT & ~vec1)<> with { } |
| x | wrap | bread.zeroinfl("x" = list(list("n" = FALSE, "vcov" = 42L, list())), "fuzz_dot1" = NULL, "fuzz_dot2" = NULL) | (INT & ~vec1)<> with { } |
| x | wrap | bread.zeroinfl(list(list("n" = as.raw(c(255)), "vcov" = -2.5, NULL, NULL)), NULL, "fuzz_dot1" = new.env()) | (INT & ~vec1)<> with { } |
| x | wrap | bread.zeroinfl("x" = list(list("n" = as.raw(c(255)), "vcov" = as.raw(c(0)), local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), list())), "fuzz_dot1" = function(...) character(0), "fuzz_dot2" = list(quote(f(x)))) | (INT & ~vec1)<> with { } |
| call | verdict | error |
|---|---|---|
| bread.zeroinfl(list("n" = as.raw(c(0, 255, 0, 255, 0)), "vcov" = raw(0), local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }))) | error_type | base::*: non-numeric argument to binary operator |
| bread.zeroinfl(list("n" = as.raw(c(255)), "vcov" = -2.5, NULL, NULL), NULL, "fuzz_dot1" = new.env()) | error_type | base::*: non-numeric argument to binary operator |
| bread.zeroinfl("x" = list("n" = as.raw(c(255)), "vcov" = as.raw(c(0)), local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), list()), "fuzz_dot1" = function(...) character(0), "fuzz_dot2" = list(quote(f(x)))) | error_type | base::*: non-numeric argument to binary operator |
| bread.zeroinfl(list("n" = as.raw(c(0)), "vcov" = 42, NULL, as.name("x"))) | error_type | base::*: non-numeric argument to binary operator |
| bread.zeroinfl("x" = list("n" = 2147483647, "vcov" = as.raw(c(0))), "fuzz_dot1" = function(...) quote(f(x))) | error_type | base::*: non-numeric argument to binary operator |
bread.zeroinfl <- function(x, ...)
{
x$vcov * x$n
}vcov — a name the prelude does not declarename: vcov
bread.mlogit <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
vcov(x) * length(residuals(x))
}model.matrix — a name the prelude does not declarename: model.matrix
bread.rlm <- function(x, ...)
{
if(!is.null(x$na.action)) class(x$na.action) <- "omit"
xmat <- model.matrix(x)
xmat <- naresid(x$na.action, xmat)
wts <- weights(x)
if(is.null(wts)) wts <- 1
res <- residuals(x)
psi_deriv <- function(z) x$psi(z, deriv = 1)
rval <- sqrt(abs(as.vector(psi_deriv(res/x$s)/x$s))) * wts * xmat
rval <- chol2inv(qr.R(qr(rval))) * nrow(xmat)
return(rval)
}UseMethod — a name the prelude does not declarename: UseMethod
estfun <- function(x, ...)
{
UseMethod("estfun")
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.lm <- function(x, ...)
{
xmat <- model.matrix(x)
xmat <- naresid(x$na.action, xmat)
if(any(alias <- is.na(coef(x)))) xmat <- xmat[, !alias, drop = FALSE]
wts <- weights(x)
if(is.null(wts)) wts <- 1
res <- residuals(x)
rval <- as.vector(res) * wts * xmat
attr(rval, "assign") <- NULL
attr(rval, "contrasts") <- NULL
if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, "frequency"))
if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))
return(rval)
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.mlm <- function(x, ...)
{
xmat <- model.matrix(x)
xmat <- naresid(x$na.action, xmat)
wts <- weights(x)
if(is.null(wts)) wts <- 1
res <- residuals(x)
cf <- coef(x)
rval <- lapply(1:NCOL(res), function(i) {
rv <- as.vector(res[,i]) * wts * xmat
colnames(rv) <- paste(colnames(cf)[i], colnames(rv), sep = ":")
rv
})
rval <- do.call("cbind", rval)
attr(rval, "assign") <- NULL
attr(rval, "contrasts") <- NULL
if(any(alias <- is.na(as.vector(cf)))) rval <- rval[, !alias, drop = FALSE]
if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, "frequency"))
if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))
return(rval)
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.glm <- function(x, ...)
{
xmat <- model.matrix(x)
xmat <- naresid(x$na.action, xmat)
if(any(alias <- is.na(coef(x)))) xmat <- xmat[, !alias, drop = FALSE]
wres <- as.vector(residuals(x, "working")) * weights(x, "working")
dispersion <- if(substr(x$family$family, 1, 17) %in% c("poisson", "binomial", "Negative Binomial")) 1
else sum(wres^2, na.rm = TRUE)/sum(weights(x, "working"), na.rm = TRUE)
rval <- wres * xmat / dispersion
attr(rval, "assign") <- NULL
attr(rval, "contrasts") <- NULL
res <- residuals(x, type = "pearson")
if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))
if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, "frequency"))
return(rval)
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.rlm <- function(x, ...)
{
xmat <- model.matrix(x)
xmat <- naresid(x$na.action, xmat)
wts <- weights(x)
if(is.null(wts)) wts <- 1
res <- residuals(x)
psi <- function(z) x$psi(z) * z
rval <- as.vector(psi(res/x$s)) * wts * xmat
attr(rval, "assign") <- NULL
attr(rval, "contrasts") <- NULL
if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))
if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, "frequency"))
return(rval)
}make.link — a name the prelude does not declarename: make.link
estfun.polr <- function(x, ...)
{
## link processing
mueta <- x$method
if(mueta == "logistic") mueta <- "logit"
mueta <- make.link(mueta)$mu.eta
## observations
xmat <- model.matrix(x)[, -1L, drop = FALSE]
n <- nrow(xmat)
k <- ncol(xmat)
m <- length(x$zeta)
mf <- model.frame(x)
y <- as.numeric(model.response(mf))
w <- model.weights(mf)
if(is.null(w)) w <- rep(1, n)
## estimates
prob <- x$fitted.values[cbind(1:n, y)]
xb <- if(k >= 1L) as.vector(xmat %*% x$coefficients) else rep(0, n)
zeta <- x$zeta
lp <- cbind(0, mueta(matrix(zeta, nrow = n, ncol = m, byrow = TRUE) - xb), 0)
## estimating functions
rval <- matrix(0, nrow = n, ncol = k + m + 2L)
if(k >= 1L) rval[, 1L:k] <- (-xmat * as.vector(lp[cbind(1:n, y + 1L)] - lp[cbind(1:n, y)]))
rval[cbind(1:n, k + y)] <- -as.vector(lp[cbind(1:n, y)])
rval[cbind(1:n, k + y + 1L)] <- as.vector(lp[cbind(1:n, y + 1L)])
rval <- rval[, -c(k + 1L, k + m + 2L), drop = FALSE]
rval <- w/prob * rval
## dimnames and return
dimnames(rval) <- list(rownames(xmat), c(colnames(xmat), names(x$zeta)))
return(rval)
}estfun.clm <- function(x, ...)
{
if(x$threshold != "flexible") stop("only flexible thresholds implemented at the moment")
## link processing
mueta <- make.link(x$link)$mu.eta
## observations
xmat <- model.matrix(x)
if(length(xmat) > 1L) stop("estimating functions for scale regression not implemented yet")
xmat <- xmat$X[, -1L, drop = FALSE]
n <- nrow(xmat)
k <- ncol(xmat)
m <- length(x$alpha)
mf <- model.frame(x)
y <- as.numeric(model.response(mf))
w <- model.weights(mf)
if(is.null(w)) w <- rep(1, n)
## estimates
prob <- x$fitted.values
xb <- if(k >= 1L) as.vector(xmat %*% x$beta) else rep(0, n)
zeta <- x$alpha
lp <- cbind(0, mueta(matrix(zeta, nrow = n, ncol = m, byrow = TRUE) - xb), 0)
## estimating functions
rval <- matrix(0, nrow = n, ncol = k + m + 2L)
if(k >= 1L) rval[, 1L:k] <- (-xmat * as.vector(lp[cbind(1:n, y + 1L)] - lp[cbind(1:n, y)]))
rval[cbind(1:n, k + y)] <- -as.vector(lp[cbind(1:n, y)])
rval[cbind(1:n, k + y + 1L)] <- as.vector(lp[cbind(1:n, y + 1L)])
rval <- rval[, -c(k + 1L, k + m + 2L), drop = FALSE]
rval <- w/prob * rval
## dimnames, re-order and return
dimnames(rval) <- list(rownames(xmat), c(colnames(xmat), names(x$alpha)))
ix <- if(k >= 1L) c((k + 1L):(k + m), 1L:k) else 1L:m
return(rval[, ix, drop = FALSE])
}variable: wts expected: null & 'I1699 given: 1.<> expression may be: 1
estfun.coxph <- function(x, ...)
{
wts <- x$weights
if(is.null(wts)) wts <- 1
wts * residuals(x, type = "score", ...)
}model.frame — a name the prelude does not declarename: model.frame
estfun.survreg <- function(x, ...)
{
mf <- model.frame(x)
xmat <- model.matrix(terms(x), mf)
wts <- model.weights(mf)
if(is.null(wts)) wts <- 1
res <- residuals(x, type = "matrix")
rval <- as.vector(res[,"dg"]) * wts * xmat
if(NROW(x$var) > length(coef(x))) {
rval <- cbind(rval, res[,"ds"])
colnames(rval)[NCOL(rval)] <- "Log(scale)"
}
attr(rval, "assign") <- NULL
return(rval)
}as.vector — a name the prelude does not declarename: as.vector
estfun.nls <- function(x, ...)
{
rval <- as.vector(x$m$resid()) * x$m$gradient()
colnames(rval) <- names(coef(x))
rval
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.hurdle <- function(x, ...) {
## extract data
Y <- if(is.null(x$y)) model.response(model.frame(x)) else x$y
X <- model.matrix(x, model = "count")
Z <- model.matrix(x, model = "zero")
beta <- coef(x, model = "count")
gamma <- coef(x, model = "zero")
fulltheta <- x$theta
offset <- x$offset
if(is.list(offset)) {
offsetx <- offset$count
offsetz <- offset$zero
} else {
offsetx <- offset
offsetz <- NULL
}
if(is.null(offsetx)) offsetx <- 0
if(is.null(offsetz)) offsetz <- 0
if(x$dist$zero == "binomial") linkobj <- make.link(x$link)
wts <- weights(x)
if(is.null(wts)) wts <- 1
Y1 <- Y > 0
## count component: working residuals
eta <- as.vector(X %*% beta + offsetx)
mu <- exp(eta)
theta <- fulltheta["count"]
wres_count <- as.numeric(Y > 0) * switch(x$dist$count,
"poisson" = {
(Y - mu) - exp(ppois(0, lambda = mu, log.p = TRUE) -
ppois(0, lambda = mu, lower.tail = FALSE, log.p = TRUE) + eta)
},
"geometric" = {
(Y - mu * (Y + 1)/(mu + 1)) - exp(pnbinom(0, mu = mu, size = 1, log.p = TRUE) -
pnbinom(0, mu = mu, size = 1, lower.tail = FALSE, log.p = TRUE) - log(mu + 1) + eta)
},
"negbin" = {
(Y - mu * (Y + theta)/(mu + theta)) - exp(pnbinom(0, mu = mu, size = theta, log.p = TRUE) -
pnbinom(0, mu = mu, size = theta, lower.tail = FALSE, log.p = TRUE) +
log(theta) - log(mu + theta) + eta)
})
## zero component: working residuals
eta <- as.vector(Z %*% gamma + offsetz)
mu <- if(x$dist$zero == "binomial") linkobj$linkinv(eta) else exp(eta)
theta <- fulltheta["zero"]
wres_zero <- switch(x$dist$zero,
"poisson" = {
ifelse(Y1, exp(ppois(0, lambda = mu, log.p = TRUE) -
ppois(0, lambda = mu, lower.tail = FALSE, log.p = TRUE) + eta), -mu)
},
"geometric" = {
ifelse(Y1, exp(pnbinom(0, mu = mu, size = 1, log.p = TRUE) -
pnbinom(0, mu = mu, size = 1, lower.tail = FALSE, log.p = TRUE) - log(mu + 1) + eta), -mu/(mu + 1))
},
"negbin" = {
ifelse(Y1, exp(pnbinom(0, mu = mu, size = theta, log.p = TRUE) -
pnbinom(0, mu = mu, size = theta, lower.tail = FALSE, log.p = TRUE) +
log(theta) - log(mu + theta) + eta), -mu * theta/(mu + theta))
},
"binomial" = {
ifelse(Y1, 1/mu, -1/(1-mu)) * linkobj$mu.eta(eta)
})
## compute gradient from data
rval <- cbind(wres_count * wts * X, wres_zero * wts * Z)
colnames(rval) <- names(coef(x))
rownames(rval) <- rownames(X)
return(rval)
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.zeroinfl <- function(x, ...) {
## extract data
Y <- if(is.null(x$y)) model.response(model.frame(x)) else x$y
X <- model.matrix(x, model = "count")
Z <- model.matrix(x, model = "zero")
beta <- coef(x, model = "count")
gamma <- coef(x, model = "zero")
theta <- x$theta
offset <- x$offset
if(is.list(offset)) {
offsetx <- offset$count
offsetz <- offset$zero
} else {
offsetx <- offset
offsetz <- NULL
}
if(is.null(offsetx)) offsetx <- 0
if(is.null(offsetz)) offsetz <- 0
linkobj <- make.link(x$link)
wts <- weights(x)
if(is.null(wts)) wts <- 1
Y1 <- Y > 0
eta <- as.vector(X %*% beta + offsetx)
mu <- exp(eta)
etaz <- as.vector(Z %*% gamma + offsetz)
muz <- linkobj$linkinv(etaz)
## density for y = 0
clogdens0 <- switch(x$dist,
"poisson" = -mu,
"geometric" = dnbinom(0, size = 1, mu = mu, log = TRUE),
"negbin" = dnbinom(0, size = theta, mu = mu, log = TRUE))
dens0 <- muz * (1 - as.numeric(Y1)) + exp(log(1 - muz) + clogdens0)
## working residuals
wres_count <- switch(x$dist,
"poisson" = ifelse(Y1, Y - mu, -exp(-log(dens0) + log(1 - muz) + clogdens0 + log(mu))),
"geometric" = ifelse(Y1, Y - mu * (Y + 1)/(mu + 1), -exp(-log(dens0) +
log(1 - muz) + clogdens0 - log(mu + 1) + log(mu))),
"negbin" = ifelse(Y1, Y - mu * (Y + theta)/(mu + theta), -exp(-log(dens0) +
log(1 - muz) + clogdens0 + log(theta) - log(mu + theta) + log(mu))))
wres_zero <- ifelse(Y1, -1/(1-muz) * linkobj$mu.eta(etaz),
(linkobj$mu.eta(etaz) - exp(clogdens0) * linkobj$mu.eta(etaz))/dens0)
## compute gradient from data
rval <- cbind(wres_count * wts * X, wres_zero * wts * Z)
colnames(rval) <- names(coef(x))
rownames(rval) <- rownames(X)
return(rval)
}((x: { gradient: 'I1895, any }, ...: any) -> 'I1895)<>| parameter | change | call | returned |
|---|---|---|---|
| x | kind:lang | estfun.mlogit(quote(f(x)), c(NA_character_, "a"), "fuzz_dot1" = NULL, "fuzz_dot2" = list(NULL, function(...) as.name("x"))) | null |
estfun.mlogit <- function(x, ...) {
x$gradient
}model.matrix — a name the prelude does not declarename: model.matrix
estfun.multinom <- function(x, ...) {
xmat <- model.matrix(x)
m <- length(x$lev)
n <- nrow(xmat)
k <- ncol(xmat)
wts <- model.weights(model.frame(x))
if(is.null(wts)) wts <- rep.int(1, n)
res <- residuals(x)
if(m == 2L) res <- cbind(-res, res)
rval <- matrix(0, nrow = n, ncol = (m - 1L) * k, dimnames = list(
rownames(xmat),
as.vector(t(outer(x$lev[-1L], x$vcoefnames, paste, sep = ":")))
))
for(i in 2L:m) rval[, (i - 2L) * k + 1L:k] <- wts * res[, i] * xmat
return(rval)
}estfun — one of the package’s own names, itself untypedname: estfun
meat <- function(x, adjust = FALSE, ...)
{
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
psi <- estfun(x, ...)
k <- NCOL(psi)
n <- NROW(psi)
rval <- crossprod(as.matrix(psi))/n
if(adjust) rval <- n/(n-k) * rval
rownames(rval) <- colnames(rval) <- colnames(psi)
return(rval)
}bread — one of the package’s own names, itself untypedname: bread
sandwich <- function(x, bread. = bread, meat. = meat, ...)
{
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
if(is.function(bread.)) bread. <- bread.(x)
if(is.function(meat.)) meat. <- meat.(x, ...)
n <- NROW(estfun(x))
return(1/n * (bread. %*% meat. %*% bread.))
}estfun — one of the package’s own names, itself untypedname: estfun
vcovOPG <- function(x, adjust = FALSE, ...)
{
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
psi <- estfun(x, ...)
k <- NCOL(psi)
n <- NROW(psi)
rval <- chol2inv(qr.R(qr(psi)))
if(adjust) rval <- n/(n-k) * rval
rownames(rval) <- colnames(rval) <- colnames(psi)
return(rval)
}UseMethod — a name the prelude does not declarename: UseMethod
vcovHAC <- function(x, ...) {
UseMethod("vcovHAC")
}estfun — one of the package’s own names, itself untypedname: estfun
bwAndrews <- function(x, order.by = NULL, kernel = c("Quadratic Spectral", "Truncated",
"Bartlett", "Parzen", "Tukey-Hanning"), approx = c("AR(1)", "ARMA(1,1)"),
weights = NULL, prewhite = 1, ar.method = "ols", data = list(), ...)
{
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
kernel <- match.arg(kernel)
approx <- match.arg(approx)
prewhite <- as.integer(prewhite)
umat <- if(inherits(x, "matrix")) x else estfun(x)[,, drop = FALSE]
if(is.zoo(umat)) umat <- as.matrix(coredata(umat))
n <- nrow(umat)
k <- ncol(umat)
if(!is.null(order.by))
{
if(inherits(order.by, "formula")) {
z <- model.matrix(order.by, data = data)
z <- as.vector(z[,ncol(z)])
} else {
z <- order.by
}
index <- order(z)
} else {
index <- 1:n
}
umat <- umat[index, , drop = FALSE]
## compute weights (try to set the intercept weight to 0)
#### could be ignored by using: weights = 1
if(is.null(weights)) {
weights <- rep(1, k)
unames <- colnames(umat)
if(!is.null(unames) && "(Intercept)" %in% unames)
weights[which(unames == "(Intercept)")] <- 0
else {
res <- try(as.vector(rowMeans(estfun(x)/model.matrix(x), na.rm = TRUE)), silent = TRUE)
if(inherits(res, "try-error")) res <- try(residuals(x), silent = TRUE)
if(!inherits(res, "try-error")) weights[which(colSums((umat - res)^2) < 1e-16)] <- 0
}
if(isTRUE(all.equal(weights, rep(0, k)))) weights <- rep(1, k)
} else {
weights <- rep(weights, length.out = k)
}
if(length(weights) < 2) weights <- 1
if(prewhite > 0) {
var.fit <- try(ar(umat, order.max = prewhite, demean = FALSE, aic = FALSE, method = ar.method))
if(inherits(var.fit, "try-error")) stop(sprintf("VAR(%i) prewhitening of estimating functions failed", prewhite))
umat <- as.matrix(na.omit(var.fit$resid))
n <- n - prewhite ##??
}
if(approx == "AR(1)") {
fitAR1 <- function(x) {
rval <- tryCatch(ar(x, order.max = 1, aic = FALSE, method = "ols"),
error = function(e) return(list(ar = NA_real_, var.pred = NA_real_)))
rval <- c(rval$ar, sqrt(rval$var.pred))
names(rval) <- c("rho", "sigma")
return(rval)
}
ar.coef <- apply(umat, 2, fitAR1)
if(any(!is.finite(ar.coef))) {
ok <- apply(is.finite(ar.coef), 2L, all)
stop(paste("Cannot compute bandwidth because AR(1) approximation failed for estimating functions of:",
paste(colnames(ar.coef)[!ok], collapse = ", ")))
}
denum <- sum(weights * (ar.coef["sigma",]/(1-ar.coef["rho",]))^4)
alpha2 <- sum(weights * 4 * ar.coef["rho",]^2 * ar.coef["sigma",]^4/(1-ar.coef["rho",])^8) / denum
alpha1 <- sum(weights * 4 * ar.coef["rho",]^2 * ar.coef["sigma",]^4/((1-ar.coef["rho",])^6 * (1+ar.coef["rho",])^2)) / denum
} else {
fitARMA11 <- function(x) {
rval <- tryCatch(arima(x, order = c(1, 0, 1), include.mean = FALSE),
error = function(e) return(list(coef = c(NA_real_, NA_real_), var.pred = NA_real_)))
rval <- c(rval$coef, sqrt(rval$sigma2))
names(rval) <- c("rho", "psi", "sigma")
return(rval)
}
arma.coef <- apply(umat, 2, fitARMA11)
if(any(!is.finite(arma.coef))) {
ok <- apply(is.finite(arma.coef), 2L, all)
stop(paste("Cannot compute bandwidth because ARMA(1,1) approximation failed for estimating functions of:",
paste(colnames(arma.coef)[!ok], collapse = ", ")))
}
denum <- sum(weights * ((1 + arma.coef["psi",]) * arma.coef["sigma",]/(1-arma.coef["rho",]))^4)
alpha2 <- sum(weights * 4 * ((1 + arma.coef["rho",] * arma.coef["psi",]) * (
arma.coef["rho",] + arma.coef["psi",]))^2 * arma.coef["sigma",]^4/
(1-arma.coef["rho",])^8) / denum
alpha1 <- sum(weights * 4 * ((1 + arma.coef["rho",] * arma.coef["psi",]) * (
arma.coef["rho",] + arma.coef["psi",]))^2 * arma.coef["sigma",]^4/
((1-arma.coef["rho",])^6 * (1+arma.coef["rho",])^2)) / denum
}
rval <- switch(kernel,
"Truncated" = {0.6611 * (n * alpha2)^(1/5)},
"Bartlett" = {1.1447 * (n * alpha1)^(1/3)},
"Parzen" = {2.6614 * (n * alpha2)^(1/5)},
"Tukey-Hanning" = {1.7462 * (n * alpha2)^(1/5)},
"Quadratic Spectral" = {1.3221 * (n * alpha2)^(1/5)})
return(rval)
}bwAndrews — one of the package’s own names, itself untypedname: bwAndrews
weightsAndrews <- function(x, order.by = NULL, bw = bwAndrews,
kernel = c("Quadratic Spectral", "Truncated", "Bartlett", "Parzen", "Tukey-Hanning"),
prewhite = 1, ar.method = "ols", tol = 1e-7, data = list(), verbose = FALSE, ...)
{
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
kernel <- match.arg(kernel)
if(is.function(bw))
bw <- bw(x, order.by = order.by, kernel = kernel,
prewhite = prewhite, data = data, ar.method = ar.method, ...)
if(verbose) cat(paste("\nBandwidth chosen:", format(bw), "\n"))
n <- NROW(estfun(x)) - as.integer(prewhite)
weights <- kweights(0:(n-1)/bw, kernel = kernel)
weights <- weights[1:max(which(abs(weights) > tol))]
return(weights)
}weightsAndrews — one of the package’s own names, itself untypedname: weightsAndrews
meatHAC <- function(x, order.by = NULL, prewhite = FALSE,
weights = weightsAndrews, adjust = TRUE, diagnostics = FALSE,
ar.method = "ols", data = list(), ...)
{
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
prewhite <- as.integer(prewhite)
umat <- estfun(x, ...)[, , drop = FALSE]
if(is.zoo(umat)) umat <- as.matrix(coredata(umat))
n.orig <- n <- nrow(umat)
k <- ncol(umat)
if(!is.null(order.by))
{
if(inherits(order.by, "formula")) {
z <- model.matrix(order.by, data = data)
z <- as.vector(z[,ncol(z)])
} else {
z <- order.by
}
index <- order(z)
} else {
index <- 1:n
}
umat <- umat[index, , drop = FALSE]
if(prewhite > 0) {
var.fit <- try(ar(umat, order.max = prewhite, demean = FALSE, aic = FALSE, method = ar.method))
if(inherits(var.fit, "try-error")) stop(sprintf("VAR(%i) prewhitening of estimating functions failed", prewhite))
if(k > 1) D <- solve(diag(ncol(umat)) - apply(var.fit$ar, 2:3, sum))
else D <- as.matrix(1/(1 - sum(var.fit$ar)))
umat <- as.matrix(na.omit(var.fit$resid))
n <- n - prewhite
}
if(is.function(weights))
weights <- weights(x, order.by = order.by, prewhite = prewhite, ar.method = ar.method, data = data)
if(length(weights) > n) {
warning("more weights than observations, only first n used")
weights <- weights[1:n]
}
utu <- 0.5 * crossprod(umat) * weights[1]
wsum<-n*weights[1]/2
w2sum<-n*weights[1]^2/2
if(length(weights) > 1) {
for (ii in 2:length(weights)) {
utu <- utu + weights[ii] * crossprod(umat[1:(n-ii+1),,drop=FALSE], umat[ii:n,,drop=FALSE])
wsum <- wsum + (n-ii+1) * weights[ii]
w2sum <- w2sum + (n-ii+1) * weights[ii]^2
}
}
utu <- utu + t(utu)
## Andrews: multiply with df n/(n-k)
if(adjust) utu <- n.orig/(n.orig-k) * utu
if(prewhite > 0) {
utu <- crossprod(t(D), utu) %*% t(D)
}
wsum <- 2*wsum
w2sum <- 2*w2sum
bc <- n^2/(n^2 - wsum)
df <- n^2/w2sum
rval <- utu/n.orig
if(diagnostics) attr(rval, "diagnostics") <- list(bias.correction = bc, df = df)
return(rval)
}weightsAndrews — one of the package’s own names, itself untypedname: weightsAndrews
vcovHAC.default <- function(x, order.by = NULL, prewhite = FALSE,
weights = weightsAndrews, adjust = TRUE, diagnostics = FALSE,
sandwich = TRUE, ar.method = "ols", data = list(), ...)
{
rval <- meatHAC(x, order.by = order.by, prewhite = prewhite,
weights = weights, adjust = adjust, diagnostics = diagnostics,
ar.method = ar.method, data = data)
if(sandwich) {
diagn <- attr(rval, "diagnostics")
rval <- sandwich(x, meat. = rval, ...)
attr(rval, "diagnostics") <- diagn
}
return(rval)
}bwAndrews — one of the package’s own names, itself untypedname: bwAndrews
kernHAC <- function(x, order.by = NULL, prewhite = 1, bw = bwAndrews,
kernel = c("Quadratic Spectral", "Truncated", "Bartlett", "Parzen", "Tukey-Hanning"),
approx = c("AR(1)", "ARMA(1,1)"), adjust = TRUE, diagnostics = FALSE, sandwich = TRUE,
ar.method = "ols", tol = 1e-7, data = list(), verbose = FALSE, ...)
{
myweights <- function(x, order.by = NULL, prewhite = FALSE, ar.method = "ols", data = list())
weightsAndrews(x, order.by = order.by, prewhite = prewhite, bw = bw,
kernel = kernel, approx = approx, ar.method = ar.method, tol = tol,
data = data, verbose = verbose, ...)
vcovHAC(x, order.by = order.by, prewhite = prewhite,
weights = myweights, adjust = adjust, diagnostics = diagnostics,
sandwich = sandwich, ar.method = ar.method, data = data)
}isoacf — one of the package’s own names, itself untypedname: isoacf
weightsLumley <- function(x, order.by = NULL, C = NULL,
method = c("truncate", "smooth"), acf = isoacf, tol = 1e-7, data = list(), ...)
{
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
method <- match.arg(method)
res <- residuals(x, "response") #FIXME# available for which models?
n <- length(res)
if(!is.null(order.by))
{
if(inherits(order.by, "formula")) {
z <- model.matrix(order.by, data = data)
z <- as.vector(z[,ncol(z)])
} else {
z <- order.by
}
index <- order(z)
} else {
index <- 1:n
}
res <- res[index]
rhohat <- acf(res)
switch(method,
"truncate" = {
if(is.null(C)) C <- 4
lag <- max((1:length(rhohat))[rhohat^2*n > C])
weights <- rep(1, lag)
},
"smooth" = {
if(is.null(C)) C <- 1
weights <- C * n * rhohat^2
weights <- ifelse(weights > 1, 1, weights)
weights <- weights[1:max(which(abs(weights) > tol))]
})
return(weights)
}Invalid_argument("Variable ..._5 is already bound.")weave <- function(x, order.by = NULL, prewhite = FALSE, C = NULL,
method = c("truncate", "smooth"), acf = isoacf, adjust = FALSE,
diagnostics = FALSE, sandwich = TRUE, tol = 1e-7, data = list(), ...)
{
myweights <- function(x, order.by = NULL, prewhite = FALSE, data = list(), ...)
weightsLumley(x, order.by = order.by, prewhite = prewhite, C = C,
method = method, acf = acf, tol = tol, data = data)
vcovHAC(x, order.by = order.by, prewhite = prewhite,
weights = myweights, adjust = adjust, diagnostics = diagnostics,
sandwich = sandwich, data = data)
}dQuote — a name the prelude does not declarename: dQuote
bwNeweyWest <- function(x, order.by = NULL, kernel = c("Bartlett", "Parzen",
"Quadratic Spectral", "Truncated", "Tukey-Hanning"), weights = NULL, prewhite = 1,
ar.method = "ols", data = list(), ...)
{
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
kernel <- match.arg(kernel)
if(kernel %in% c("Truncated", "Tukey-Hanning"))
stop(paste("Automatic bandwidth selection only available for ",
dQuote("Bartlett"), ", ", dQuote("Parzen"), " and ", dQuote("Quadratic Spectral"),
" kernel. Use ", sQuote("bwAndrews"), " instead.", sep = ""))
prewhite <- as.integer(prewhite)
umat <- if(inherits(x, "matrix")) x else estfun(x)[,, drop = FALSE]
if(is.zoo(umat)) umat <- as.matrix(coredata(umat))
n <- nrow(umat)
k <- ncol(umat)
if(!is.null(order.by))
{
if(inherits(order.by, "formula")) {
z <- model.matrix(order.by, data = data)
z <- as.vector(z[,ncol(z)])
} else {
z <- order.by
}
index <- order(z)
} else {
index <- 1:n
}
umat <- umat[index, , drop = FALSE]
## compute weights (try to set the intercept weight to 0)
#### could be ignored by using: weights = 1
if(is.null(weights)) {
weights <- rep(1, k)
unames <- colnames(umat)
if(!is.null(unames) && "(Intercept)" %in% unames)
weights[which(unames == "(Intercept)")] <- 0
else {
res <- try(as.vector(rowMeans(estfun(x)/model.matrix(x), na.rm = TRUE)), silent = TRUE)
if(inherits(res, "try-error")) res <- try(residuals(x), silent = TRUE)
if(!inherits(res, "try-error")) weights[which(colSums((umat - res)^2) < 1e-16)] <- 0
}
if(all(weights <= 0)) weights <- rep(1, length.out = k)
} else {
weights <- rep(weights, length.out = k)
}
if(length(weights) < 2) weights <- 1
## select lag truncation according to Table II C. from Newey & West (1994)
mrate <- switch(kernel,
"Bartlett" = 2/9,
"Parzen" = 4/25,
"Quadratic Spectral" = 2/25)
m <- floor(ifelse(prewhite > 0, 3, 4) * (n/100)^mrate)
if(prewhite > 0) {
var.fit <- try(ar(umat, order.max = prewhite, demean = FALSE, aic = FALSE, method = ar.method))
if(inherits(var.fit, "try-error")) stop(sprintf("VAR(%i) prewhitening of estimating functions failed", prewhite))
umat <- as.matrix(na.omit(var.fit$resid))
n <- n - prewhite
}
## compute weighted variances
hw <- umat %*% weights
sigmaj <- function(j) sum(hw[1:(n-j)] * hw[(j+1):n])/n
sigma <- sapply(0:m, sigmaj)
s0 <- sigma[1] + 2*sum(sigma[-1])
s1 <- 2 * sum(1:m * sigma[-1])
s2 <- 2 * sum((1:m)^2 * sigma[-1])
## use parameters as in Table I B.
## choose 1/(2*q + 1)
qrate <- 1/(2 * ifelse(kernel == "Bartlett", 1, 2) + 1)
## compute gamma
rval <- switch(kernel,
"Bartlett" = { 1.1447 * ((s1/s0)^2)^qrate },
"Parzen" = { 2.6614 * ((s2/s0)^2)^qrate },
"Quadratic Spectral" = { 1.3221 * ((s2/s0)^2)^qrate })
## compute bandwidth
rval <- rval * (n + prewhite)^qrate
## rval is not truncated. This is done in NeweyWest(),
## but bwNeweyWest() can also be used without truncation.
return(rval)
}bwNeweyWest — one of the package’s own names, itself untypedname: bwNeweyWest
NeweyWest <- function(x, lag = NULL,
order.by = NULL, prewhite = TRUE, adjust = FALSE,
diagnostics = FALSE, sandwich = TRUE, ar.method = "ols", data = list(),
verbose = FALSE)
{
if(is.null(lag)) lag <- floor(bwNeweyWest(x,
order.by = order.by, prewhite = prewhite,
ar.method = ar.method, data = data))
if(verbose) cat(paste("\nLag truncation parameter chosen:", lag, "\n"))
myweights <- seq(1, 0, by = -(1/(lag + 1)))
vcovHAC(x, order.by = order.by, prewhite = prewhite,
weights = myweights, adjust = adjust, diagnostics = diagnostics,
sandwich = sandwich, ar.method = ar.method, data = data)
}coredata — a name the prelude does not declarename: coredata
lrvar <- function(x, type = c("Andrews", "Newey-West"), prewhite = TRUE, adjust = TRUE, ...)
{
## data and model
x <- coredata(x)
m <- lm(x ~ 1)
## vcov matrix
type <- match.arg(gsub("-", "", tolower(type), fixed = TRUE),
c("andrews", "neweywest"))
vc <- switch(type,
"andrews" = kernHAC(m, prewhite = prewhite, adjust = adjust, ...),
"neweywest" = NeweyWest(m, prewhite = prewhite, adjust = adjust, ...))
## set names or drop dimension for univariate series
if(NCOL(x) > 1) {
rownames(vc) <- colnames(vc) <- colnames(x)
} else {
vc <- drop(vc)
}
return(vc)
}.vcovBSenv <- new.env()UseMethod — a name the prelude does not declarename: UseMethod
vcovBS <- function(x, ...) {
UseMethod("vcovBS")
}Failure("Unsupported argument after an ellipsis.")vcovBS.default <- function(x, cluster = NULL, R = 250, start = FALSE, type = "xy", ..., fix = FALSE, use = "pairwise.complete.obs", applyfun = NULL, cores = NULL, center = "mean")
{
## set up return value with correct dimension and names
cf0 <- coef(x)
k <- length(cf0)
n <- nobs0(x)
rval <- matrix(0, nrow = k, ncol = k, dimnames = list(names(cf0), names(cf0)))
## try to figure out environment for update()
env <- try(environment(terms(x)))
if(inherits(env, "try-error")) env <- NULL
## cluster can either be supplied explicitly or
## be an attribute of the model...FIXME: other specifications?
if (is.null(cluster)) cluster <- attr(x, "cluster")
## resort to cross-section if no clusters are supplied
if (is.null(cluster)) cluster <- 1L:n
## collect 'cluster' variables in a data frame
if(inherits(cluster, "formula")) {
cluster_tmp <- if("Formula" %in% loadedNamespaces()) { ## FIXME to suppress potential warnings due to | in Formula
suppressWarnings(expand.model.frame(x, cluster, na.expand = FALSE))
} else {
expand.model.frame(x, cluster, na.expand = FALSE)
}
cluster <- model.frame(cluster, cluster_tmp, na.action = na.pass)
} else {
cluster <- as.data.frame(cluster)
}
## handle omitted or excluded observations
if((n != NROW(cluster)) && !is.null(x$na.action) && (class(x$na.action) %in% c("exclude", "omit"))) {
cluster <- cluster[-x$na.action, , drop = FALSE]
}
if(NROW(cluster) != n) stop("number of observations in 'cluster' and 'nobs()' do not match")
## catch NAs in cluster -> need to be addressed in the model object by the user
if(anyNA(cluster)) stop("cannot handle NAs in 'cluster': either refit the model without the NA observations in 'cluster' or impute the NAs")
## for multi-way clustering: set up interaction patterns
p <- NCOL(cluster)
if (p > 1L) {
cl <- lapply(1L:p, function(i) combn(1L:p, i, simplify = FALSE))
cl <- unlist(cl, recursive = FALSE)
sign <- sapply(cl, function(i) (-1L)^(length(i) + 1L))
paste_ <- function(...) paste(..., sep = "_")
for (i in (p + 1L):length(cl)) {
cluster <- cbind(cluster, Reduce(paste_, unclass(cluster[, cl[[i]] ]))) ## faster than: interaction()
}
} else {
cl <- list(1)
sign <- 1
}
## apply infrastructure for refitting models
if(is.null(applyfun)) {
applyfun <- if(is.null(cores)) {
lapply
} else {
if(.Platform$OS.type == "windows") {
cl_cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cl_cores))
function(X, FUN, ...) parallel::parLapply(cl = cl_cores, X, FUN, ...)
} else {
function(X, FUN, ...) parallel::mclapply(X, FUN, ..., mc.cores = cores)
}
}
}
## use starting values?
assign(".vcovBSstart", if(isTRUE(start)) coef(x) else NULL, envir = .vcovBSenv)
## xy bootstrap vs. jackknife
type <- match.arg(tolower(type), c("xy", "jackknife", "fractional"))
## bootstrap for each cluster dimension
for (i in 1L:length(cl)) {
## cluster structure
cli <- if(type != "fractional") {
split(seq_along(cluster[[i]]), cluster[[i]])
} else {
factor(cluster[[i]], levels = unique(cluster[[i]]))
}
## bootstrap fitting function via update()
bootfit <- function(j, ...) {
clj <- switch(type,
"xy" = {
unlist(cli[sample(names(cli), length(cli), replace = TRUE)])
},
"jackknife" = {
unlist(cli[-j])
},
"fractional" = {
fw <- rexp(nlevels(cli))
fw <- fw[cli]/mean(fw)
mw <- weights(x)
j <- if(is.null(mw)) fw else mw * fw
})
assign(".vcovBSsubset", clj, envir = .vcovBSenv)
up <- if(is.null(.vcovBSenv$.vcovBSstart)) {
if(type != "fractional") {
update(x, subset = .vcovBSenv$.vcovBSsubset, ..., evaluate = FALSE)
} else {
update(x, weights = .vcovBSenv$.vcovBSsubset, ..., evaluate = FALSE)
}
} else {
if(type != "fractional") {
update(x, subset = .vcovBSenv$.vcovBSsubset, start = .vcovBSenv$.vcovBSstart, ..., evaluate = FALSE)
} else {
update(x, weights = .vcovBSenv$.vcovBSsubset, start = .vcovBSenv$.vcovBSstart, ..., evaluate = FALSE)
}
}
up <- eval(up, envir = env, enclos = parent.frame())
coef(up)
}
## for jackknife the number of replications is always the number of "observations" (cluster units)
if(type == "jackknife") R <- length(cli)
## actually refit
cf <- applyfun(1L:R, bootfit, ...)
## aggregate across cluster variables
if(type == "jackknife") {
cf <- do.call("cbind", cf)
center <- match.arg(center, c("mean", "estimate"))
rval <- rval + sign[i] * (R - 1L)/R * tcrossprod(cf - if(center == "mean") rowMeans(cf) else cf0)
} else {
cf <- do.call("rbind", cf)
rval <- rval + sign[i] * cov(cf, use = use)
}
}
## clean up starting values again
remove(".vcovBSstart", envir = .vcovBSenv)
## check (and fix) if sandwich is not positive semi-definite
if(fix && any((eig <- eigen(rval, symmetric = TRUE))$values < 0)) {
eig$values <- pmax(eig$values, 0)
rval[] <- crossprod(sqrt(eig$values) * t(eig$vectors))
}
return(rval)
}Failure("Unsupported positional argument after a named one.")vcovBS.lm <- function(x, cluster = NULL, R = 250, type = "xy", ..., fix = FALSE, use = "pairwise.complete.obs", applyfun = NULL, cores = NULL, qrjoint = FALSE, center = "mean")
{
## set up return value with correct dimension and names
cf0 <- coef(x)
k <- length(cf0)
n <- nobs(x)
rval <- matrix(0, nrow = k, ncol = k, dimnames = list(names(cf0), names(cf0)))
## cluster can either be supplied explicitly or
## be an attribute of the model...FIXME: other specifications?
if (is.null(cluster)) cluster <- attr(x, "cluster")
## resort to cross-section if no clusters are supplied
if (is.null(cluster)) cluster <- 1L:n
## collect 'cluster' variables in a data frame
if(inherits(cluster, "formula")) {
cluster_tmp <- if("Formula" %in% loadedNamespaces()) { ## FIXME to suppress potential warnings due to | in Formula
suppressWarnings(expand.model.frame(x, cluster, na.expand = FALSE))
} else {
expand.model.frame(x, cluster, na.expand = FALSE)
}
cluster <- model.frame(cluster, cluster_tmp, na.action = na.pass)
} else {
cluster <- as.data.frame(cluster)
}
## handle omitted or excluded observations
if((n != NROW(cluster)) && !is.null(x$na.action) && (class(x$na.action) %in% c("exclude", "omit"))) {
cluster <- cluster[-x$na.action, , drop = FALSE]
}
if(NROW(cluster) != n) stop("number of observations in 'cluster' and 'nobs()' do not match")
## catch NAs in cluster -> need to be addressed in the model object by the user
if(anyNA(cluster)) stop("cannot handle NAs in 'cluster': either refit the model without the NA observations in 'cluster' or impute the NAs")
## for multi-way clustering: set up interaction patterns
p <- NCOL(cluster)
if (p > 1L) {
cl <- lapply(1L:p, function(i) combn(1L:p, i, simplify = FALSE))
cl <- unlist(cl, recursive = FALSE)
sign <- sapply(cl, function(i) (-1L)^(length(i) + 1L))
paste_ <- function(...) paste(..., sep = "_")
for (i in (p + 1L):length(cl)) {
cluster <- cbind(cluster, Reduce(paste_, unclass(cluster[, cl[[i]] ]))) ## faster than: interaction()
}
} else {
cl <- list(1)
sign <- 1
}
## bootstrap type: xy vs. residual vs. wild (in various flavors)
if(is.function(type)) {
wild <- type
type <- "user"
} else {
wild <- function(n) NULL
}
type <- match.arg(gsub("wild-", "", tolower(type), fixed = TRUE),
c("xy", "jackknife", "fractional", "residual", "wild", "webb", "rademacher", "mammen", "norm", "user"))
if(type == "wild") type <- "rademacher"
## set up wild bootstrap function
wild <- switch(type,
"rademacher" = function(n) sample(c(-1, 1), n, replace = TRUE),
"mammen" = function(n) sample(c(-1, 1) * (sqrt(5) + c(-1, 1))/2, n, replace = TRUE,
prob = (sqrt(5) + c(1, -1))/(2 * sqrt(5))),
"norm" = function(n) rnorm(n),
"webb" = function(n) sample(c(-sqrt((3:1)/2), sqrt((1:3)/2)), n, replace = TRUE),
wild
)
## model information: original response, weights, and design matrix or the corresponding fitted/residuals/QR
y <- if(!is.null(x$y)) {
x$y
} else if(!is.null(x$model)) {
model.response(x$model)
} else {
model.response(model.frame(x))
}
wts <- if(is.null(x$weights)) rep.int(1, n) else x$weights
off <- if(is.null(x$offset)) rep.int(0, n) else x$offset
xfit <- if(type %in% c("xy", "jackknife", "fractional")) model.matrix(x) else list(fit = x$fitted.values, res = x$residuals, qr = x$qr)
## apply infrastructure for refitting models
if(is.null(applyfun)) {
applyfun <- if(is.null(cores)) {
lapply
} else {
if(.Platform$OS.type == "windows") {
cl_cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cl_cores))
function(X, FUN, ...) parallel::parLapply(cl = cl_cores, X, FUN, ...)
} else {
function(X, FUN, ...) parallel::mclapply(X, FUN, ..., mc.cores = cores)
}
}
}
## bootstrap for each cluster dimension
for (i in 1L:length(cl)) {
## cluster structure
cli <- if(type %in% c("xy", "jackknife", "residual")) {
split(seq_along(cluster[[i]]), cluster[[i]])
} else {
factor(cluster[[i]], levels = unique(cluster[[i]]))
}
## check for balanced clusters in residual bootstrap
if(type == "residual" && length(unique(sapply(cli, length))) > 1L) {
warning("residual bootstrap is not well-defined for unbalanced clusters")
}
## bootstrap fitting function
bootfit <- switch(type,
"xy" = function(j, ...) {
j <- unlist(cli[sample(names(cli), length(cli), replace = TRUE)])
.lm.fit(xfit[j, , drop = FALSE] * sqrt(wts[j]), (y[j] - off[j]) * sqrt(wts[j]), ...)$coefficients
},
"jackknife" = function(j, ...) {
j <- unlist(cli[-j])
.lm.fit(xfit[j, , drop = FALSE] * sqrt(wts[j]), (y[j] - off[j]) * sqrt(wts[j]), ...)$coefficients
},
"fractional" = function(j, ...) {
fw <- rexp(nlevels(cli))
fw <- fw[cli]/mean(fw)
.lm.fit(xfit * sqrt(wts * fw), (y - off) * sqrt(wts * fw), ...)$coefficients
},
"residual" = function(j, ...) {
j <- unlist(cli[sample(names(cli), length(cli), replace = TRUE)])
yboot <- xfit$fit + xfit$res[j]
yboot <- (yboot - off) * sqrt(wts)
if(qrjoint) yboot else qr.coef(xfit$qr, yboot)
},
function(j, ...) {
j <- wild(nlevels(cli))
yboot <- xfit$fit + xfit$res * j[cli]
yboot <- (yboot - off) * sqrt(wts)
if(qrjoint) yboot else qr.coef(xfit$qr, yboot)
}
)
## for jackknife the number of replications is always the number of "observations" (cluster units)
if(type == "jackknife") R <- length(cli)
## actually refit
cf <- applyfun(1L:R, bootfit, ...)
## aggregate across cluster variables
if(type == "jackknife") {
cf <- do.call("cbind", cf)
center <- match.arg(center, c("mean", "estimate"))
rval <- rval + sign[i] * (R - 1L)/R * tcrossprod(cf - if(center == "mean") rowMeans(cf) else cf0)
} else {
cf <- if(qrjoint && type != "xy") t(qr.coef(xfit$qr, do.call("cbind", cf))) else do.call("rbind", cf)
rval <- rval + sign[i] * cov(cf, use = use)
}
}
## check (and fix) if sandwich is not positive semi-definite
if(fix && any((eig <- eigen(rval, symmetric = TRUE))$values < 0)) {
eig$values <- pmax(eig$values, 0)
rval[] <- crossprod(sqrt(eig$values) * t(eig$vectors))
}
return(rval)
}Failure("Unsupported argument after an ellipsis.")vcovBS.glm <- function(x, cluster = NULL, R = 250, start = FALSE, type = "xy", ..., fix = FALSE, use = "pairwise.complete.obs", applyfun = NULL, cores = NULL, center = "mean")
{
## set up return value with correct dimension and names
cf0 <- coef(x)
if(identical(start, TRUE)) start <- cf0
if(identical(start, FALSE)) start <- NULL
k <- length(cf0)
n <- nobs(x)
rval <- matrix(0, nrow = k, ncol = k, dimnames = list(names(cf0), names(cf0)))
## cluster can either be supplied explicitly or
## be an attribute of the model...FIXME: other specifications?
if (is.null(cluster)) cluster <- attr(x, "cluster")
## resort to cross-section if no clusters are supplied
if (is.null(cluster)) cluster <- 1L:n
## collect 'cluster' variables in a data frame
if(inherits(cluster, "formula")) {
cluster_tmp <- if("Formula" %in% loadedNamespaces()) { ## FIXME to suppress potential warnings due to | in Formula
suppressWarnings(expand.model.frame(x, cluster, na.expand = FALSE))
} else {
expand.model.frame(x, cluster, na.expand = FALSE)
}
cluster <- model.frame(cluster, cluster_tmp, na.action = na.pass)
} else {
cluster <- as.data.frame(cluster)
}
## handle omitted or excluded observations
if((n != NROW(cluster)) && !is.null(x$na.action) && (class(x$na.action) %in% c("exclude", "omit"))) {
cluster <- cluster[-x$na.action, , drop = FALSE]
}
if(NROW(cluster) != n) stop("number of observations in 'cluster' and 'nobs()' do not match")
## catch NAs in cluster -> need to be addressed in the model object by the user
if(anyNA(cluster)) stop("cannot handle NAs in 'cluster': either refit the model without the NA observations in 'cluster' or impute the NAs")
## for multi-way clustering: set up interaction patterns
p <- NCOL(cluster)
if (p > 1L) {
cl <- lapply(1L:p, function(i) combn(1L:p, i, simplify = FALSE))
cl <- unlist(cl, recursive = FALSE)
sign <- sapply(cl, function(i) (-1L)^(length(i) + 1L))
paste_ <- function(...) paste(..., sep = "_")
for (i in (p + 1L):length(cl)) {
cluster <- cbind(cluster, Reduce(paste_, unclass(cluster[, cl[[i]] ]))) ## faster than: interaction()
}
} else {
cl <- list(1)
sign <- 1
}
## model information: original response, design matrix, fitting method
y <- if(!is.null(x$y)) {
x$y
} else if(!is.null(x$model)) {
model.response(x$model)
} else {
model.response(model.frame(x))
}
xfit <- model.matrix(x)
method <- x$method
## apply infrastructure for refitting models
if(is.null(applyfun)) {
applyfun <- if(is.null(cores)) {
lapply
} else {
if(.Platform$OS.type == "windows") {
cl_cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cl_cores))
function(X, FUN, ...) parallel::parLapply(cl = cl_cores, X, FUN, ...)
} else {
function(X, FUN, ...) parallel::mclapply(X, FUN, ..., mc.cores = cores)
}
}
}
## xy bootstrap vs. jackknife
type <- match.arg(tolower(type), c("xy", "jackknife", "fractional"))
## bootstrap for each cluster dimension
for (i in 1L:length(cl))
{
## cluster structure
cli <- if(type != "fractional") {
split(seq_along(cluster[[i]]), cluster[[i]])
} else {
factor(cluster[[i]], levels = unique(cluster[[i]]))
}
## bootstrap fitting function
bootfit <- function(j, ...) {
if(type == "xy") {
j <- unlist(cli[sample(names(cli), length(cli), replace = TRUE)])
wts <- 1
} else if(type == "jackknife") {
j <- unlist(cli[-j])
wts <- 1
} else if(type == "fractional") {
j <- 1L:n
wts <- rexp(nlevels(cli))
wts <- wts[cli]/mean(wts)
}
eval(
call(if(is.function(method)) "method" else method,
x = xfit[j, , drop = FALSE], y = y[j], weights = x$prior.weights[j] * wts, offset = x$offset[j],
family = x$family, start = start, control = x$control, intercept = attr(x$terms, "intercept") > 0)
)$coefficients
}
## for jackknife the number of replications is always the number of "observations" (cluster units)
if(type == "jackknife") R <- length(cli)
## actually refit
cf <- applyfun(1L:R, bootfit, ...)
## aggregate across cluster variables
if(type == "jackknife") {
cf <- do.call("cbind", cf)
center <- match.arg(center, c("mean", "estimate"))
rval <- rval + sign[i] * (R - 1L)/R * tcrossprod(cf - if(center == "mean") rowMeans(cf) else cf0)
} else {
cf <- do.call("rbind", cf)
rval <- rval + sign[i] * cov(cf, use = use)
}
}
## check (and fix) if sandwich is not positive semi-definite
if(fix && any((eig <- eigen(rval, symmetric = TRUE))$values < 0)) {
eig$values <- pmax(eig$values, 0)
rval[] <- crossprod(sqrt(eig$values) * t(eig$vectors))
}
return(rval)
}solve — a name the prelude does not declarename: solve
matrixinverse <- function(X, tol = .Machine$double.eps^(1/1.3)) {
if((ncol(X) == 1L) && (nrow(X) == 1L)) return(1/X)
inv <- try(solve(X), silent = TRUE)
if(!inherits(inv, "try-error")) return(inv)
Xsvd <- svd(X)
ok <- Xsvd$d > max(tol * Xsvd$d[1L], 0)
inv <- Xsvd$v[, ok, drop = FALSE] %*% ((1/Xsvd$d[ok]) * t(Xsvd$u[, ok, drop = FALSE]))
return(inv)
}isSymmetric — a name the prelude does not declarename: isSymmetric
matrixpower <- function(X, p, symmetric = NULL, tol = .Machine$double.eps^(1/1.3)) {
if((ncol(X) == 1L) && (nrow(X) == 1L)) return(X^p)
if(is.null(symmetric)) symmetric <- isSymmetric(X)
Xeig <- eigen(X, symmetric = symmetric)
if(is.complex(Xeig$values)) {
if(any(abs(Im(Xeig$values)) > tol)) warning("complex eigen values of X")
Xeig$values <- Re(Xeig$values)
Xeig$vectors <- Re(Xeig$vectors)
}
Xeig$values[Xeig$values < tol] <- 0
# if(any(Xeig$values < 0)) stop("matrix is not positive semidefinite")
if(symmetric) {
Xeig$vectors %*% ((Xeig$values^p) * t(Xeig$vectors))
} else {
Xeig$vectors %*% ((Xeig$values^p) * matrixinverse(Xeig$vectors))
}
}Failure("Unsupported argument after an ellipsis.")meatCL <- function(x, cluster = NULL, type = NULL, cadjust = TRUE, multi0 = FALSE, ...)
{
## extract estimating functions / aka scores
if (is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
ef <- estfun(x, ...)
k <- NCOL(ef)
n <- NROW(ef)
## set up return value with correct dimension and names
rval <- matrix(0, nrow = k, ncol = k,
dimnames = list(colnames(ef), colnames(ef)))
## cluster can either be supplied explicitly or
## be an attribute of the model...FIXME: other specifications?
if (is.null(cluster)) cluster <- attr(x, "cluster")
## resort to cross-section if no clusters are supplied
if (is.null(cluster)) cluster <- 1L:n
## collect 'cluster' variables in a data frame
if(inherits(cluster, "formula")) {
cluster_tmp <- if("Formula" %in% loadedNamespaces()) { ## FIXME to suppress potential warnings due to | in Formula
suppressWarnings(expand.model.frame(x, cluster, na.expand = FALSE))
} else {
expand.model.frame(x, cluster, na.expand = FALSE)
}
cluster <- model.frame(cluster, cluster_tmp, na.action = na.pass)
} else {
cluster <- as.data.frame(cluster)
}
## handle omitted or excluded observations
if((n != NROW(cluster)) && !is.null(x$na.action) && (class(x$na.action) %in% c("exclude", "omit"))) {
cluster <- cluster[-x$na.action, , drop = FALSE]
}
if(NROW(cluster) != n) stop("number of observations in 'cluster' and 'estfun()' do not match")
## catch NAs in cluster -> need to be addressed in the model object by the user
if(anyNA(cluster)) stop("cannot handle NAs in 'cluster': either refit the model without the NA observations in 'cluster' or impute the NAs")
## for multi-way clustering: set up interaction patterns
p <- NCOL(cluster)
if (p > 1L) {
cl <- lapply(1L:p, function(i) combn(1L:p, i, simplify = FALSE))
cl <- unlist(cl, recursive = FALSE)
sign <- sapply(cl, function(i) (-1L)^(length(i) + 1L))
paste_ <- function(...) paste(..., sep = "_")
for (i in (p + 1L):length(cl)) {
cluster <- cbind(cluster, Reduce(paste_, unclass(cluster[, cl[[i]] ]))) ## faster than: interaction()
}
if(multi0) cluster[[length(cl)]] <- 1L:n
} else {
cl <- list(1)
sign <- 1
}
## number of clusters (and cluster interactions)
g <- sapply(1L:length(cl), function(i) {
if(is.factor(cluster[[i]])) {
length(levels(cluster[[i]]))
} else {
length(unique(cluster[[i]]))
}
})
#gmin <- min(g[1L:p])
## FIXME: additional argument for optionally using only smallest number of clusters?
## See also Cameron, Gelbach and Miller (2011, page 241)
#if(FALSE) g[] <- gmin
## type of model
is_lm <- function(object) class(object)[1L] == "lm"
is_glm <- function(object) class(object)[1L] == "glm"
## type of bias correction
if(is.null(type)) {
type <- if(is_lm(x)) "HC1" else "HC0"
}
type <- match.arg(type, c("HC", "HC0", "HC1", "HC2", "HC3"))
if(type == "HC") type <- "HC0"
## building blocks for HC2/HC3
if(type %in% c("HC2", "HC3"))
{
if(any(g == n)) h <- hatvalues(x)
if(!all(g == n)) {
if(!(is_lm(x) || is_glm(x))) warning("clustered HC2/HC3 are only applicable to (generalized) linear regression models")
## regressor matrix
X <- model.matrix(x)
if(any(alias <- is.na(coef(x)))) X <- X[, !alias, drop = FALSE]
attr(X, "assign") <- NULL
## working weights
w <- weights(x, "working")
## (X'X)^(-1)
XX1 <- if(is.null(w)) chol2inv(qr.R(qr(X))) else chol2inv(qr.R(qr(X * sqrt(w))))
## working residuals
res <- rowMeans(ef/X, na.rm = TRUE)
res[apply(abs(ef) < .Machine$double.eps, 1L, all)] <- 0
}
}
## add OPG for each cluster-aggregated estfun
for (i in 1L:length(cl))
{
## estimating functions for aggregation by i-th clustering variable
efi <- ef
## add cluster adjustment g/(g - 1) or not?
## only exception: HC0 adjustment for multiway clustering at "last interaction"
adj <- if(multi0 & (i == length(cl))) {
if(type == "HC1") (n - k)/(n - 1L) else 1
} else {
if(cadjust) g[i]/(g[i] - 1L) else 1
}
## HC2/HC3
if(type %in% c("HC2", "HC3")) {
if(g[i] == n) {
efi <- if(type == "HC2") {
efi/sqrt(1 - h)
} else {
efi/(1 - hatvalues(x))
}
} else {
for(j in unique(cluster[[i]])) {
ij <- which(cluster[[i]] == j)
Hij <- if(is.null(w)) {
X[ij, , drop = FALSE] %*% XX1 %*% t(X[ij, , drop = FALSE])
} else {
X[ij, , drop = FALSE] %*% XX1 %*% t(X[ij, , drop = FALSE]) %*% diag(w[ij], nrow = length(ij), ncol = length(ij))
}
Hij <- if(type == "HC2") {
matrixpower(diag(length(ij)) - Hij, -0.5)
} else {
solve(diag(length(ij)) - Hij)
}
efi[ij, ] <- drop(Hij %*% res[ij]) * X[ij, , drop = FALSE]
}
}
## "inverse" cluster adjustment that Bell & McCaffrey (2002) and hence also
## Cameron & Miller (2005, Eq. 25) recommend for HC3 (but not HC2)
## -> canceled out again if cadjust = TRUE
efi <- sqrt((g[i] - 1L)/g[i]) * efi
}
## aggregate within cluster levels
efi <- if(g[i] < n) apply(efi, 2L, rowsum, cluster[[i]]) else efi
## aggregate across cluster variables
rval <- rval + sign[i] * adj * crossprod(efi)/n
}
## HC1 adjustment with residual degrees of freedom: (n - 1)/(n - k)
if(type == "HC1") rval <- (n - 1L)/(n - k) * rval
return(rval)
}meatCL — one of the package’s own names, itself untypedname: meatCL
vcovCL <- function(x, cluster = NULL, type = NULL, sandwich = TRUE, fix = FALSE, ...)
{
## compute meat of sandwich
rval <- meatCL(x, cluster = cluster, type = type, ...)
## full sandwich
if(sandwich) rval <- sandwich(x, meat. = rval)
## check (and fix) if sandwich is not positive semi-definite
if(fix && any((eig <- eigen(rval, symmetric = TRUE))$values < 0)) {
eig$values <- pmax(eig$values, 0)
rval[] <- crossprod(sqrt(eig$values) * t(eig$vectors))
}
return(rval)
}UseMethod — a name the prelude does not declarename: UseMethod
vcovHC <- function(x, ...) {
UseMethod("vcovHC")
}model.matrix — a name the prelude does not declarename: model.matrix
meatHC <- function(x,
type = c("HC3", "const", "HC", "HC0", "HC1", "HC2", "HC4", "HC4m", "HC5"),
omega = NULL, ...)
{
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
## extract X and residual degrees of freedom
X <- model.matrix(x)
if(any(alias <- is.na(coef(x)))) X <- X[, !alias, drop = FALSE]
attr(X, "assign") <- NULL
n <- NROW(X)
df <- n - NCOL(X)
## hat values
diaghat <- try(hatvalues(x), silent = TRUE)
## the following might work, but "intercept" is also claimed for "coxph"
## res <- if(attr(terms(x), "intercept") > 0) estfun(x)[,1] else rowMeans(estfun(x)/X, na.rm = TRUE)
## hence better rely on
ef <- estfun(x, ...)
if (!all(dim(X) == dim(ef))) stop("cannot match dimension of model.matrix and estfun to obtain working residuals")
res <- rowMeans(ef/X, na.rm = TRUE)
## handle rows with just zeros
all0 <- apply(abs(ef) < .Machine$double.eps, 1L, all)
res[all0] <- 0
## in case of lm/glm and type = "const" re-obtain the working residuals
if(any(all0) && substr(type, 1L, 1L) == "c") {
if(inherits(x, "glm")) {
res <- as.vector(residuals(x, "working")) * weights(x, "working")
if(!(substr(x$family$family, 1L, 17L) %in% c("poisson", "binomial", "Negative Binomial"))) {
res <- res * sum(weights(x, "working"), na.rm = TRUE) / sum(res^2, na.rm = TRUE)
}
} else if(inherits(x, "lm")) {
res <- as.vector(residuals(x))
if(!is.null(weights(x))) res <- res * weights(x)
}
}
## if omega not specified, set up using type
if(is.null(omega)) {
type <- match.arg(type)
if(type == "HC") type <- "HC0"
switch(type,
"const" = { omega <- function(residuals, diaghat, df) rep(1, length(residuals)) * sum(residuals^2)/df },
"HC0" = { omega <- function(residuals, diaghat, df) residuals^2 },
"HC1" = { omega <- function(residuals, diaghat, df) residuals^2 * length(residuals)/df },
"HC2" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat) },
"HC3" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat)^2 },
"HC4" = { omega <- function(residuals, diaghat, df) {
n <- length(residuals)
p <- as.integer(round(sum(diaghat), digits = 0))
delta <- pmin(4, n * diaghat/p)
residuals^2 / (1 - diaghat)^delta
}},
"HC4m" = { omega <- function(residuals, diaghat, df) {
gamma <- c(1.0, 1.5) ## as recommended by Cribari-Neto & Da Silva
n <- length(residuals)
p <- as.integer(round(sum(diaghat), digits = 0))
delta <- pmin(gamma[1], n * diaghat/p) + pmin(gamma[2], n * diaghat/p)
residuals^2 / (1 - diaghat)^delta
}},
"HC5" = { omega <- function(residuals, diaghat, df) {
k <- 0.7 ## as recommended by Cribari-Neto et al.
n <- length(residuals)
p <- as.integer(round(sum(diaghat), digits = 0))
delta <- pmin(n * diaghat/p, pmax(4, n * k * max(diaghat)/p))
residuals^2 / sqrt((1 - diaghat)^delta)
}}
)
## check hat values
if(type != "const") {
if(type %in% c("HC0", "HC1")) {
idx <- if(inherits(diaghat, "try-error")) abs(res)/sqrt(mean(res^2)) < .Machine$double.eps^0.75 else diaghat > 1 - sqrt(.Machine$double.eps)
msg <- "%s covariances become (close to) singular if hat values are (close to) 1 as for observation(s) %s"
} else {
if(inherits(diaghat, "try-error")) stop(sprintf("hatvalues() could not be extracted successfully but are needed for %s", type))
idx <- diaghat > 1 - sqrt(.Machine$double.eps)
msg <- "%s covariances are numerically unstable for hat values close to 1 (and undefined if exactly 1) as for observation(s) %s"
}
if(any(idx)) {
idx <- if(is.null(rownames(X))) as.character(which(idx)) else rownames(X)[idx]
if(length(idx) > 10L) idx <- c(idx[1L:10L], "...")
warning(sprintf(msg, type, paste(idx, collapse = ", ")))
}
}
}
## process omega
if(is.function(omega)) omega <- omega(res, diaghat, df)
rval <- sqrt(omega) * X
rval <- crossprod(rval)/n
return(rval)
}meatHC — one of the package’s own names, itself untypedname: meatHC
vcovHC.default <- function(x,
type = c("HC3", "const", "HC", "HC0", "HC1", "HC2", "HC4", "HC4m", "HC5"),
omega = NULL, sandwich = TRUE, ...)
{
type <- match.arg(type)
rval <- meatHC(x, type = type, omega = omega)
if(sandwich) rval <- sandwich(x, meat. = rval, ...)
return(rval)
}model.matrix — a name the prelude does not declarename: model.matrix
vcovHC.mlm <- function(x,
type = c("HC3", "const", "HC", "HC0", "HC1", "HC2", "HC4", "HC4m", "HC5"),
omega = NULL, sandwich = TRUE, ...)
{
## compute meat "by hand" because meatHC() can not deal with
## residual "matrices"
## ensure that NAs are omitted
if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
## regressors and df
X <- model.matrix(x)
attr(X, "assign") <- NULL
if(any(alias <- apply(coef(x), 1, function(z) all(is.na(z))))) X <- X[, !alias, drop = FALSE]
n <- NROW(X)
df <- n - NCOL(X)
## hat values and residuals
diaghat <- hatvalues(x)
res <- residuals(x)
## if omega not specified, set up using type
if(is.null(omega)) {
type <- match.arg(type)
if(type == "HC") type <- "HC0"
switch(type,
"const" = {
warning("not implemented for 'mlm' objects, using vcov() instead")
return(vcov(x))
},
"HC0" = { omega <- function(residuals, diaghat, df) residuals^2 },
"HC1" = { omega <- function(residuals, diaghat, df) residuals^2 * length(residuals)/df },
"HC2" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat) },
"HC3" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat)^2 },
"HC4" = { omega <- function(residuals, diaghat, df) {
n <- length(residuals)
p <- as.integer(round(sum(diaghat), digits = 0))
delta <- pmin(4, n * diaghat/p)
residuals^2 / (1 - diaghat)^delta
}},
"HC4m" = { omega <- function(residuals, diaghat, df) {
gamma <- c(1.0, 1.5)
n <- length(residuals)
p <- as.integer(round(sum(diaghat), digits = 0))
delta <- pmin(gamma[1], n * diaghat/p) + pmin(gamma[2], n * diaghat/p)
residuals^2 / (1 - diaghat)^delta
}},
"HC5" = { omega <- function(residuals, diaghat, df) {
k <- 0.7
n <- length(residuals)
p <- as.integer(round(sum(diaghat), digits = 0))
delta <- pmin(n * diaghat/p, pmax(4, n * k * max(diaghat)/p))
residuals^2 / sqrt((1 - diaghat)^delta)
}}
)
## check hat values (if necessary)
if(type %in% c("HC2", "HC3", "HC4", "HC4m", "HC5")) {
if(inherits(diaghat, "try-error")) stop(sprintf("hatvalues() could not be extracted successfully but are needed for %s", type))
id <- which(diaghat > 1 - sqrt(.Machine$double.eps))
if(length(id) > 0L) {
id <- if(is.null(rownames(X))) as.character(id) else rownames(X)[id]
if(length(id) > 10L) id <- c(id[1L:10L], "...")
warning(sprintf("%s cannot be computed due to observations with hatvalue = 1: %s", type, paste(id, collapse = ", ")))
}
}
}
## process omega
omega <- apply(res, 2, function(r) omega(r, diaghat, df))
## compute crossproduct X' Omega X
rval <- lapply(1:ncol(omega), function(i) as.vector(sign(res[,i]) * sqrt(omega[,i])) * X)
rval <- do.call("cbind", rval)
rval <- crossprod(rval)/n
colnames(rval) <- rownames(rval) <- colnames(vcov(x))
## if necessary compute full sandwich
if(sandwich) rval <- sandwich(x, meat. = rval, ...)
return(rval)
}UseMethod — a name the prelude does not declarename: UseMethod
vcovJK <- function(x, ...) {
UseMethod("vcovJK")
}vcovBS — one of the package’s own names, itself untypedname: vcovBS
vcovJK.default <- function(x, cluster = NULL, center = "mean", ...) {
center <- match.arg(center, c("mean", "estimate"))
vcovBS(x, cluster = cluster, center = center, type = "jackknife", ...)
}File "Rsem/lang/PAst.ml", line 210, characters 14-20: Assertion failed
meatPC <- function(x, cluster = NULL, order.by = NULL, pairwise = FALSE, kronecker = TRUE, ...)
{
## extract estimating functions / aka scores
if (is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
ef <- estfun(x, ...)
n <- NROW(ef)
## FIXME: The return value only has to be set up this way if
## it is filled componentwise. But at the moment the whole matrix is
## computed in one big matrix computation.
## rval <- matrix(0, nrow = NCOL(ef), ncol = NCOL(ef),
## dimnames = list(colnames(ef), colnames(ef)))
## cluster can either be supplied explicitly or
## be an attribute of the model
if(is.null(cluster)) cluster <- attr(x, "cluster")
## cluster (and potentially order.by) may be a formula
if(inherits(cluster, "formula")) {
## merge if both cluster and order.by are formula: ~ cluster + order.by
if(inherits(order.by, "formula")) {
cluster_orderby <- ~ cluster + order.by
cluster_orderby[[2L]][[3L]] <- order.by[[2L]]
cluster_orderby[[2L]][[2L]] <- cluster[[2L]]
cluster <- cluster_orderby
order.by <- NULL
}
## get variable(s) from expanded model frame
cluster_tmp <- if("Formula" %in% loadedNamespaces()) { ## FIXME to suppress potential warnings due to | in Formula
suppressWarnings(expand.model.frame(x, cluster, na.expand = FALSE))
} else {
expand.model.frame(x, cluster, na.expand = FALSE)
}
cluster <- model.frame(cluster, cluster_tmp, na.action = na.pass)
## handle omitted or excluded observations
if((n != NROW(cluster)) && !is.null(x$na.action) && (class(x$na.action) %in% c("exclude", "omit"))) {
cluster <- cluster[-x$na.action, , drop = FALSE]
}
}
## cluster can also be a list with both indexes
if(is.list(cluster)) {
if(length(cluster) > 1L & is.null(order.by)) order.by <- cluster[[2L]]
cluster <- cluster[[1L]]
}
## longitudinal time variable
if(is.null(order.by)) order.by <- attr(x, "order.by")
if(is.null(order.by)) {
ix <- make.unique(as.character(cluster))
ix <- strsplit(ix, ".", fixed = TRUE)
ix <- sapply(ix, "[", 2L)
ix[is.na(ix)] <- "0"
order.by <- as.integer(ix) + 1L
}
## handle omitted or excluded observations in both cluster and/or order.by
## (again, in case the formula interface was not used)
if(any(n != c(NROW(cluster), NROW(order.by))) && !is.null(x$na.action) && class(x$na.action) %in% c("exclude", "omit")) {
if(n != NROW(cluster)) cluster <- cluster[-x$na.action]
if(n != NROW(order.by)) order.by <- order.by[-x$na.action]
}
## catch NAs in cluster/order.by -> need to be addressed in the model object by the user
if(anyNA(cluster) || anyNA(order.by)) stop("cannot handle NAs in 'cluster' or 'order.by': either refit the model without the NA observations or impute the NAs")
## model matrix
X <- model.matrix(x)
if (any(alias <- is.na(coef(x)))) X <- X[, !alias, drop = FALSE]
attr(X, "assign") <- NULL
## working residuals
if (!all(dim(X) == dim(ef))) stop("cannot match dimension of model.matrix and estfun to obtain working residuals")
res <- rowMeans(ef/X, na.rm = TRUE)
res[apply(abs(ef) < .Machine$double.eps, 1L, all)] <- 0
## balanced panel
balanced <- isTRUE(length(unique(table(cluster, order.by))) == 1L)
if(balanced) {
## split residuals by cluster
e <- split(res, cluster)
## bind into matrix
e <- do.call("cbind", e)
## set up omega
N <- prod(dim(e))
t <- dim(e)[1L]
n <- dim(e)[2L]
sigma <- crossprod(e) / t
if(kronecker) {
omega <- kronecker(sigma, diag(1L, t))
omega <- t(X) %*% omega %*% X / N
} else {
xx <- split(X, cluster)
xxCL <- lapply(1L:n, function(i) matrix(xx[[i]], t, ncol(X)))
omega <- Reduce("+", lapply(1L:n, function(j) Reduce("+", lapply(1L:n, function(i) sigma[j,i] * t(xxCL[[j]]) %*% xxCL[[i]] / N))))
}
}
## unbalanced panel
if(!balanced) {
pair <- data.frame(cluster = cluster, order.by = order.by)
num <- dim(pair)[1L]
pair$res <- res
pair <- data.frame(pair, X)
Tij <- expand.grid(cluster = unique(cluster), order.by = unique(order.by))
pair <- merge(pair, Tij, by = c("cluster", "order.by"), all = TRUE)
## balance panel
if(!pairwise) {
## extract "full" clusters
rem <- subset(pair$order.by, is.na(pair$res))
pairX <- as.matrix(pair[, 4L:dim(pair)[2L]])
pairX[is.na(pairX)] <- 0
pair[which(pair$order.by %in% rem), 3L:dim(X)[2L]] <- NA
pairNA <- na.omit(pair)
pair[is.na(pair)] <- 0
res <- pairNA[, 3L]
clpairNA <- pairNA[, 1L]
clpair <- pair[, 1L]
## split residuals by cluster
e <- split(res, clpairNA)
## bind into matrix
e <- do.call("cbind", e)
## set up omega
t <- dim(e)[1L]
n <- dim(e)[2L]
tt <- length(unique(order.by))
sigma <- crossprod(e) / t
if(kronecker) {
omega <- kronecker(sigma, diag(1L, tt))
omega <- t(pairX) %*% omega %*% pairX / num
} else {
xx <- split(pairX, clpair)
xxCL <- lapply(1L:n, function(i) matrix(xx[[i]], tt, ncol(X)))
omega <- Reduce("+", lapply(1L:n, function(j) Reduce("+", lapply(1L:n, function(i) sigma[j,i] * t(xxCL[[j]]) %*% xxCL[[i]] / num))))
}
} else {
## use pairwise calculation for omega (Bailey and Katz, 2011)
N <- dim(X)[1L]
e <- pair[, 3L]
X <- pair[, 4L:dim(pair)[2L]]
narows <- apply(!is.na.data.frame(X), 1, prod)
namatrix <- matrix(narows, length(unique(cluster)), length(unique(order.by)), byrow = TRUE)
namatrix <- t(namatrix)
denoma <- crossprod(namatrix)
X[is.na(X)] <- 0L
## set up omega
e <- matrix(e, length(unique(cluster)), length(unique(order.by)), byrow = TRUE)
e[is.na(e)] <- 0L
e <- t(e)
sigma <- crossprod(e) / denoma
if(kronecker) {
omega <- kronecker(sigma, diag(1L, NROW(e)))
X <- as.matrix(X)
X[is.na(X)] <- 0L
omega <- t(X) %*% omega %*% X / N
} else {
t <- length(unique(pair$order.by))
n <- length(unique(pair$cluster))
xx <- split(X, pair$cluster)
xxCL <- lapply(1L:n, function(i) as.matrix(xx[[i]], t, ncol(X)))
omega <- Reduce("+", lapply(1L:n, function(j) Reduce("+", lapply(1L:n, function(i) sigma[j,i] * t(xxCL[[j]]) %*% xxCL[[i]] / N))))
}
}
}
rval <- omega
return(rval = rval)
}meatPC — one of the package’s own names, itself untypedname: meatPC
vcovPC <- function(x, cluster = NULL, order.by = NULL, pairwise = FALSE, sandwich = TRUE, fix = FALSE, ...)
{
## compute meat of sandwich
rval <- meatPC(x, cluster = cluster, order.by = order.by, pairwise = pairwise, ...)
## full sandwich
if (sandwich) rval <- sandwich(x, meat. = rval)
## check (and fix) if sandwich is not positive semi-definite
if (fix && any((eig <- eigen(rval, symmetric = TRUE))$values < 0)) {
eig$values <- pmax(eig$values, 0)
rval[] <- crossprod(sqrt(eig$values) * t(eig$vectors))
}
return(rval)
}estfun — one of the package’s own names, itself untypedname: estfun
meatPL <- function(x, cluster = NULL, order.by = NULL,
kernel = "Bartlett", lag = "NW1987", bw = NULL, adjust = TRUE, aggregate = TRUE, ...) ## adjust/cadjust?
{
## extract estimating functions / aka scores
if (is.list(x) && !is.null(x$na.action)) class(x$na.action) <- "omit"
ef <- estfun(x, ...)
k <- NCOL(ef)
n <- NROW(ef)
## cluster can either be supplied explicitly or
## be an attribute of the model...FIXME: other specifications?
if(is.null(cluster)) cluster <- attr(x, "cluster")
## cluster (and potentially order.by) may be a formula
if(inherits(cluster, "formula")) {
## merge if both cluster and order.by are formula: ~ cluster + order.by
if(inherits(order.by, "formula")) {
cluster_orderby <- ~ cluster + order.by
cluster_orderby[[2L]][[3L]] <- order.by[[2L]]
cluster_orderby[[2L]][[2L]] <- cluster[[2L]]
cluster <- cluster_orderby
order.by <- NULL
}
## get variable(s) from expanded model frame
cluster_tmp <- if("Formula" %in% loadedNamespaces()) { ## FIXME to suppress potential warnings due to | in Formula
suppressWarnings(expand.model.frame(x, cluster, na.expand = FALSE))
} else {
expand.model.frame(x, cluster, na.expand = FALSE)
}
cluster <- model.frame(cluster, cluster_tmp, na.action = na.pass)
## handle omitted or excluded observations
if(n != NROW(cluster) && !is.null(x$na.action) && class(x$na.action) %in% c("exclude", "omit")) {
cluster <- cluster[-x$na.action, , drop = FALSE]
}
}
## cluster can also be a list with both indexes
if(is.list(cluster)) {
if(length(cluster) > 1L & is.null(order.by)) order.by <- cluster[[2L]]
cluster <- cluster[[1L]]
}
## Newey-West type standard errors if neither cluster nor order.by is specified
if(is.null(cluster) && is.null(order.by)) cluster <- rep(1, n)
## resort to cross-section if no clusters are supplied
if(is.null(cluster)) cluster <- 1L:n
## longitudinal time variable
if(is.null(order.by)) order.by <- attr(x, "order.by")
if(is.null(order.by)) {
ix <- make.unique(as.character(cluster))
ix <- strsplit(ix, ".", fixed = TRUE)
ix <- sapply(ix, "[", 2L)
ix[is.na(ix)] <- "0"
order.by <- as.integer(ix) + 1L
}
## handle omitted or excluded observations in both cluster and/or order.by
## (again, in case the formula interface was not used)
if(any(n != c(NROW(cluster), NROW(order.by))) && !is.null(x$na.action) && class(x$na.action) %in% c("exclude", "omit")) {
if(n != NROW(cluster)) cluster <- cluster[-x$na.action]
if(n != NROW(order.by)) order.by <- order.by[-x$na.action]
}
## catch NAs in cluster/order.by -> need to be addressed in the model object by the user
if(anyNA(cluster) || anyNA(order.by)) stop("cannot handle NAs in 'cluster' or 'order.by': either refit the model without the NA observations or impute the NAs")
## reorder scores and cluster/time variables
index <- order(order.by)
ef <- ef[index, , drop = FALSE]
order.by <- order.by[index]
cluster <- cluster[index]
## aggregate within time periods?
if(aggregate) {
nt <- length(unique(order.by))
if(nt < n) {
ef <- if(nt == 1L) {
matrix(colSums(ef), nrow = 1L, dimnames = list(NULL, colnames(ef)))
} else {
apply(ef, 2L, tapply, order.by, sum)
}
}
nt <- NROW(ef)
nc <- length(unique(cluster))
} else {
order.by <- as.integer(factor(order.by))
nt <- order.by[length(order.by)]
cluster <- as.integer(factor(cluster))
nc <- cluster[length(cluster)]
rownames(ef) <- paste(order.by, cluster, sep = "-")
}
## lag/bandwidth selection
if(is.character(lag)) {
if(lag == "P2009") lag <- "max"
switch(match.arg(lag, c("max", "NW1987", "NW1994")),
"max" = {
lag <- nt - 1L
},
"NW1987" = {
lag <- floor(nt^(1/4))
},
"NW1994" = {
lag <- floor(4L * (nt / 100L)^(2/9))
}
)}
if(is.numeric(lag)) lag <- lag
if(is.null(lag) & is.null(bw)) lag <- nt - 1L
if(!is.null(lag) & is.null(bw)) bw <- lag + 1
## set up kernel weights up to maximal number of lags
weights <- kweights(0L:(nt - 1L)/bw, kernel = kernel)
weights <- weights[1L:max(which(abs(weights) > 0))]
rval <- 0.5 * crossprod(ef) * weights[1L]
if(length(weights) > 1L) {
for (ii in 2L:length(weights)) {
rval <- rval + weights[ii] * if(aggregate) {
## Driscoll & Kraay (1998)
crossprod(ef[1L:(nt - ii + 1L), , drop = FALSE], ef[ii:nt, , drop = FALSE])
} else {
## restricting cross-sectional and cross-serial correlation to zero
## assure to use only clusters where both lags in the crossprod exist
ix1 <- paste(rep(1L:(nt - ii + 1L), each = nc), rep(1L:nc, nt - ii + 1L), sep = "-")
ix2 <- paste(rep(ii:nt, each = nc), rep(1L:nc, nt - ii + 1L), sep = "-")
ok <- (ix1 %in% rownames(ef)) & (ix2 %in% rownames(ef))
crossprod(ef[ix1[ok], , drop = FALSE], ef[ix2[ok], , drop = FALSE])
}
}
}
rval <- rval + t(rval)
if(adjust) rval <- n/(n - k) * rval
return(rval/n)
}meatPL — one of the package’s own names, itself untypedname: meatPL
vcovPL <- function(x, cluster = NULL, order.by = NULL,
kernel = "Bartlett", sandwich = TRUE, fix = FALSE, ...)
{
## compute meat of sandwich
rval <- meatPL(x, cluster = cluster, order.by = order.by, kernel = kernel, ...)
## full sandwich
if(sandwich) rval <- sandwich(x, meat. = rval)
## check (and fix) if sandwich is not positive semi-definite
if(fix && any((eig <- eigen(rval, symmetric = TRUE))$values < 0)) {
eig$values <- pmax(eig$values, 0)
rval[] <- crossprod(sqrt(eig$values) * t(eig$vectors))
}
return(rval)
}