← all packages

sandwich

no native code · R: 67 definitions, 6 typed strict, 39 gradual, prelude debt 35 · fuzzing: 4 definitions, 0 unsound, 4 accept calls outside their domain · tyr dc7f1a7 · Rsem 7bcb45f · NativeSem 770a1eb · rstt 2b2696f unpinned

R definitions

named top-level definitions
67 / 67 (100.0%)
not blocked by an unbound native symbol
67 / 67 (100.0%)
typed, gradual
39 / 67 (58.2%)
typed, strict
6 / 67 (9.0%)
35 of the strict failures are a name missing from the prelude.
mode
67 / 67

R definitions 67

R/auxiliary.R

nobs0 skipped

error detail
Invalid_argument("Variable ..._5 is already bound.")
timing: 0.018 s
source
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)
}
R/auxiliary.R:1

vcov0 untypeabletyped

unbound variable (line 9)
unbound: vcov — a name the prelude does not declare
error detail
name: vcov
gradual mode: typed
any
timing: 0.036 s
source
vcov0	<- if(!is.null(vcov)) vcov else {
  if("stats4" %in% loadedNamespaces()) stats4::vcov else stats::vcov
}
R/auxiliary.R:9

kweights untypeabletimeout

unbound variable (line 31)
unbound: ifelse — a name the prelude does not declare
error detail
name: ifelse
gradual mode: timeout
timing: 5.77 s
source
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
    }
  )
}
R/auxiliary.R:13

pava.blocks untypeable

untypeable application of base::[] (line 95)
error detail
argument: @(DBL | 'w, 1.<> | 'I835 & (CHR | DBL | INT | LGL | RAW))
failing call: base::[](NA_real_, as.raw(0))
timing: 1.89 s
source
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)  
}
R/auxiliary.R:87

isoacf untypeabletyped

unbound variable (line 61)
unbound: sqrt — a name the prelude does not declare
error detail
name: sqrt
gradual mode: typed
((x: any, lagmax: any?, weave1: any?) -> any)<>
timing: 0.114 s
source
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)
}
R/auxiliary.R:59
R/bread.R

bread untypeabletyped

unbound variable (line 3)
unbound: UseMethod — a name the prelude does not declare
error detail
name: UseMethod
gradual mode: typed
((x: any, ...: any) -> any)<>
timing: 0.003 s
source
bread <- function(x, ...)
{
  UseMethod("bread")
}
R/bread.R:1

bread.default untypeable

unbound variable (line 7)
unbound: nobs0 — one of the package’s own names, itself untyped
error detail
name: nobs0
timing: 0.005 s
source
bread.default <- function(x, ...) {
  nobs0(x) * vcov0(x, ...)
}
R/bread.R:6

bread.lm untypeabletyped

unbound variable (line 13)
unbound: summary.lm — a name the prelude does not declare
error detail
name: summary.lm
gradual mode: typed
((x: { na.action: <...>, any }, ...: any) | (x: { na.action: null, any }, ...: any) -> any)<>
timing: 0.243 s
source
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])))
}
R/bread.R:10

bread.mlm untypeabletyped

unbound variable (line 20)
unbound: coef — a name the prelude does not declare
error detail
name: coef
gradual mode: typed
((x: { na.action: <...>, any }, ...: any) | (x: { na.action: null, any }, ...: any) -> any)<>
timing: 0.274 s
source
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)
}
R/bread.R:17

bread.glm untypeabletyped

unbound variable (line 33)
unbound: summary — a name the prelude does not declare
error detail
name: summary
gradual mode: typed
((x: { na.action: <...>, family: { family: vec, any }, any }, ...: any) | (x: { na.action: null, family: { family: vec, any }, any }, ...: any) -> any)<>
timing: 0.285 s
source
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)
}
R/bread.R:30

bread.nls untypeabletyped

unbound variable (line 43)
unbound: summary — a name the prelude does not declare
error detail
name: summary
gradual mode: typed
((x: { na.action: <...>, any }, ...: any) | (x: { na.action: null, any }, ...: any) -> any)<>
timing: 0.246 s
source
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])))
}
R/bread.R:40

bread.polr untypeabletyped

unbound variable (line 49)
unbound: vcov — a name the prelude does not declare
error detail
name: vcov
gradual mode: typed
((x: { n: any, any }, ...: any) -> any)<>
timing: 0.005 s
source
bread.polr <- function(x, ...)
{
  vcov(x) * x$n
}
R/bread.R:47

bread.clm untypeabletyped

unbound variable (line 54)
unbound: vcov — a name the prelude does not declare
error detail
name: vcov
gradual mode: typed
((x: { n: any, any }, ...: any) -> any)<>
timing: 0.005 s
source
bread.clm <- function(x, ...)
{
  vcov(x) * x$n
}
R/bread.R:52

bread.survreg typed accepts outside

∀'a,`a. (((x: { naive.var: (INT | dbl & v('a))<. | `a>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: (INT | dbl & v('a))<. | `a>, any }, ...: any) -> (INT | (DBL | INT) & v('a))<. | `a>)&((x: { naive.var: DBL1<. | `a>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: DBL1<. | `a>, any }, ...: any) -> DBL1<. | `a>)&((x: { naive.var: dbl1<. | `a>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: dbl1<. | `a>, any }, ...: any) -> dbl1<. | `a>))<>
timing: 3.69 s
fuzzing: 20 inside (16 ok, 4 error type) · 8 outside (5 rejected, 3 accepted)
type drawn from: (((x: { naive.var: (INT | dbl & v('I1183))<. | `I113>, linear.predictors: any, any }, ...: any) | (x: { naive.var: null, linear.predictors: any, var: (INT | dbl & v('I1183))<. | `I113>, any }, ...: any) -> (INT | (DBL | INT) & v('I1183))<. | `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>))<>

Accepted outside the domain x: 3

parameterchangecallreturned
xkind:envbread.survreg(new.env(), function(...) local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), character(0))(INT & ~vec1)<> with { }
xunwrapbread.survreg(list(), "fuzz_dot1" = NULL)(INT & ~vec1)<> with { }
xwrapbread.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 { }

Other calls inside the domain

callverdicterror
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_typebase::*: 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_typebase::*: 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_typebase::*: non-numeric argument to binary operator
bread.survreg(list("linear.predictors" = NULL, "naive.var" = NULL, "var" = as.raw(c(255))))error_typebase::*: non-numeric argument to binary operator
source
bread.survreg <- function(x, ...)
  length(x$linear.predictors) * if(is.null(x$naive.var)) x$var else x$naive.var
R/bread.R:57

bread.gam untypeabletyped

unbound variable (line 63)
unbound: summary — a name the prelude does not declare
error detail
name: summary
gradual mode: typed
((x: { na.action: <...>, any }, ...: any) | (x: { na.action: null, any }, ...: any) -> any)<>
timing: 0.237 s
source
bread.gam <- function(x, ...)
{
  if(!is.null(x$na.action)) class(x$na.action) <- "omit"
  sx <- summary(x)
  sx$cov.unscaled * sx$n
}
R/bread.R:60

bread.coxph untypeabletyped

unbound variable (line 70)
unbound: coef — a name the prelude does not declare
error detail
name: coef
gradual mode: typed
((x: { n: <@"*", ...>, naive.var: null, var: any, any }, ...: any) | (x: { n: <@"*", ...>, naive.var: ~null, any }, ...: any) | (x: { n: dbl<~@"*", ...>, naive.var: dbl, any }, ...: any) | (x: { n: dbl<~@"*", ...>, naive.var: null, var: dbl, any }, ...: any) -> any)<>
timing: 3.31 s
source
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)
}
R/bread.R:67

bread.hurdle typed accepts outside

∀'a,`a. (((x: { n: (dbl & v('a))<`a>, vcov: (dbl & v('a))<@"*", `a>, any }, ...: any) -> (INT | (DBL | INT) & v('a))<`a>)&((x: { n: DBL1<`a>, vcov: dbl1<@"*", `a>, any }, ...: any) | (x: { n: dbl1<`a>, vcov: DBL1<@"*", `a>, any }, ...: any) -> DBL1<`a>)&((x: { n: any, vcov: <@"*", ...>, any }, ...: any) -> (DBL | INT)<difftime> | LGL<>)&((x: { n: dbl1<`a>, vcov: dbl1<@"*", `a>, any }, ...: any) -> dbl1<`a>))<>
timing: 10.25 s
fuzzing: 13 inside (8 ok, 5 error type) · 8 outside (5 rejected, 3 accepted)
type drawn from: (((x: { n: (dbl & v('I1285))<`I122>, vcov: (dbl & v('I1285))<@"*", `I122>, any }, ...: any) -> (INT | (DBL | INT) & v('I1285))<`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>))<>

Accepted outside the domain x: 3

parameterchangecallreturned
xdropbread.hurdle(new.env())(INT & ~vec1)<> with { }
xkind:langbread.hurdle(quote(f(x)), as.name("x"), "fuzz_dot1" = NULL)(INT & ~vec1)<> with { }
xwrapbread.hurdle(list(list("n" = FALSE, "vcov" = TRUE, NA)))(INT & ~vec1)<> with { }

Other calls inside the domain

callverdicterror
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_typebase::*: 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_typebase::*: 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_typebase::*: 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_typebase::*: non-numeric argument to binary operator
bread.hurdle("x" = list("n" = FALSE, "vcov" = as.raw(c(0))), "fuzz_dot1" = new.env())error_typebase::*: non-numeric argument to binary operator
source
bread.hurdle <- function(x, ...)
{
  x$vcov * x$n
}
R/bread.R:74

bread.zeroinfl typed accepts outside

∀'a,`a. (((x: { n: (dbl & v('a))<`a>, vcov: (dbl & v('a))<@"*", `a>, any }, ...: any) -> (INT | (DBL | INT) & v('a))<`a>)&((x: { n: DBL1<`a>, vcov: dbl1<@"*", `a>, any }, ...: any) | (x: { n: dbl1<`a>, vcov: DBL1<@"*", `a>, any }, ...: any) -> DBL1<`a>)&((x: { n: any, vcov: <@"*", ...>, any }, ...: any) -> (DBL | INT)<difftime> | LGL<>)&((x: { n: dbl1<`a>, vcov: dbl1<@"*", `a>, any }, ...: any) -> dbl1<`a>))<>
timing: 10.44 s
fuzzing: 14 inside (9 ok, 5 error type) · 8 outside (2 rejected, 6 accepted)
type drawn from: (((x: { n: (dbl & v('I1301))<`I126>, vcov: (dbl & v('I1301))<@"*", `I126>, any }, ...: any) -> (INT | (DBL | INT) & v('I1301))<`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>))<>

Accepted outside the domain x: 6

parameterchangecallreturned
xkind:nullbread.zeroinfl("x" = NULL)(INT & ~vec1)<> with { }
xkind:nullbread.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 { }
xwrapbread.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 { }
xwrapbread.zeroinfl("x" = list(list("n" = FALSE, "vcov" = 42L, list())), "fuzz_dot1" = NULL, "fuzz_dot2" = NULL)(INT & ~vec1)<> with { }
xwrapbread.zeroinfl(list(list("n" = as.raw(c(255)), "vcov" = -2.5, NULL, NULL)), NULL, "fuzz_dot1" = new.env())(INT & ~vec1)<> with { }
xwrapbread.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 { }

Other calls inside the domain

callverdicterror
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_typebase::*: 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_typebase::*: 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_typebase::*: non-numeric argument to binary operator
bread.zeroinfl(list("n" = as.raw(c(0)), "vcov" = 42, NULL, as.name("x")))error_typebase::*: non-numeric argument to binary operator
bread.zeroinfl("x" = list("n" = 2147483647, "vcov" = as.raw(c(0))), "fuzz_dot1" = function(...) quote(f(x)))error_typebase::*: non-numeric argument to binary operator
source
bread.zeroinfl <- function(x, ...)
{
  x$vcov * x$n
}
R/bread.R:79

bread.mlogit untypeabletyped

unbound variable (line 87)
unbound: vcov — a name the prelude does not declare
error detail
name: vcov
gradual mode: typed
((x: { na.action: <...>, any }, ...: any) | (x: { na.action: null, any }, ...: any) -> any)<>
timing: 0.220 s
source
bread.mlogit <- function(x, ...)
{
  if(!is.null(x$na.action)) class(x$na.action) <- "omit"
  vcov(x) * length(residuals(x))
}
R/bread.R:84

bread.rlm untypeabletyped

unbound variable (line 93)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
gradual mode: typed
((x: { na.action: <...>, psi: arrow, s: any, any }, ...: any) | (x: { na.action: null, psi: arrow, s: any, any }, ...: any) -> any)<>
timing: 0.241 s
source
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)
}
R/bread.R:90
R/estfun.R

estfun untypeabletyped

unbound variable (line 3)
unbound: UseMethod — a name the prelude does not declare
error detail
name: UseMethod
gradual mode: typed
((x: any, ...: any) -> any)<>
timing: 0.003 s
source
estfun <- function(x, ...)
{
  UseMethod("estfun")
}
R/estfun.R:1

estfun.lm untypeable

unbound variable (line 8)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
timing: 0.028 s
source
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)
}
R/estfun.R:6

estfun.mlm untypeable

unbound variable (line 24)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
timing: 0.047 s
source
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)
}
R/estfun.R:22

estfun.glm untypeable

unbound variable (line 46)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
timing: 0.052 s
source
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)
}
R/estfun.R:44

estfun.rlm untypeabletimeout

unbound variable (line 63)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
gradual mode: timeout
timing: 0.031 s
source
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)
}
R/estfun.R:61

estfun.polr untypeabletyped

unbound variable (line 82)
unbound: make.link — a name the prelude does not declare
error detail
name: make.link
gradual mode: typed
((x: { method: any, zeta: any, fitted.values: any, coefficients: any, any }, ...: any) -> any)<>
timing: 0.197 s
source
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)
}
R/estfun.R:77

estfun.clm typed empty return

((x: { threshold: ~"flexible", any }, ...: any) -> empty)<>
timing: 0.256 s
source
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])
}
R/estfun.R:113

estfun.coxph untypeabletyped

untypeable assignment (line 155)
error detail
variable: wts
expected: null & 'I1557
given: 1.<>
expression may be: 1
gradual mode: typed
((x: { weights: ~null, any }, ...: any) -> any)<>
timing: 0.067 s
source
estfun.coxph <- function(x, ...)
{
  wts <- x$weights
  if(is.null(wts)) wts <- 1
  wts * residuals(x, type = "score", ...)
}
R/estfun.R:152

estfun.survreg untypeabletyped

unbound variable (line 161)
unbound: model.frame — a name the prelude does not declare
error detail
name: model.frame
gradual mode: typed
((x: { var: any, any }, ...: any) -> any)<>
timing: 0.028 s
source
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)
}
R/estfun.R:159

estfun.nls untypeabletyped

unbound variable (line 178)
unbound: as.vector — a name the prelude does not declare
error detail
name: as.vector
gradual mode: typed
((x: { m: { resid: @() -> any, gradient: @() -> any, any }, any }, ...: any) -> any)<>
timing: 0.073 s
source
estfun.nls <- function(x, ...)
{
  rval <- as.vector(x$m$resid()) * x$m$gradient()
  colnames(rval) <- names(coef(x))
  rval
}
R/estfun.R:176

estfun.hurdle untypeabletimeout

unbound variable (line 186)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
gradual mode: timeout
timing: 0.409 s
source
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)
}
R/estfun.R:183

estfun.zeroinfl untypeabletimeout

unbound variable (line 260)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
gradual mode: timeout
timing: 0.253 s
source
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)
}
R/estfun.R:257

estfun.mlogit typed accepts outside

∀'a. ((x: { gradient: 'a, any }, ...: any) -> 'a)<>
timing: 0.025 s
fuzzing: 20 inside (20 ok) · 8 outside (7 rejected, 1 accepted)
type drawn from: ((x: { gradient: 'I1739, any }, ...: any) -> 'I1739)<>

Accepted outside the domain x: 1

parameterchangecallreturned
xkind:langestfun.mlogit(quote(f(x)), c(NA_character_, "a"), "fuzz_dot1" = NULL, "fuzz_dot2" = list(NULL, function(...) as.name("x")))null
source
estfun.mlogit <- function(x, ...) {
  x$gradient
}
R/estfun.R:310

estfun.multinom untypeable

unbound variable (line 315)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
timing: 0.064 s
source
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)
}
R/estfun.R:314
R/sandwich.R

meat untypeabletyped

unbound variable (line 13)
unbound: estfun — one of the package’s own names, itself untyped
error detail
name: estfun
gradual mode: typed
((x: { na.action: <...>, any }, adjust: any?, ...: any) | (x: { na.action: null, any }, adjust: any?, ...: any) -> any)<>
timing: 0.654 s
source
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)
}
R/sandwich.R:10

sandwich untypeable

unbound variable (line 1)
unbound: bread — one of the package’s own names, itself untyped
error detail
name: bread
timing: 0.088 s
source
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.))
}
R/sandwich.R:1

vcovOPG untypeabletyped

unbound variable (line 25)
unbound: estfun — one of the package’s own names, itself untyped
error detail
name: estfun
gradual mode: typed
((x: { na.action: <...>, any }, adjust: any?, ...: any) | (x: { na.action: null, any }, adjust: any?, ...: any) -> any)<>
timing: 0.688 s
source
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)
}
R/sandwich.R:22
R/vcovHAC.R

vcovHAC untypeabletyped

unbound variable (line 6)
unbound: UseMethod — a name the prelude does not declare
error detail
name: UseMethod
gradual mode: typed
((x: any, ...: any) -> any)<>
timing: 0.003 s
source
vcovHAC <- function(x, ...) {
  UseMethod("vcovHAC")
}
R/vcovHAC.R:5

bwAndrews untypeable

unbound variable (line 140)
unbound: estfun — one of the package’s own names, itself untyped
error detail
name: estfun
timing: 11.44 s
source
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)  
}
R/vcovHAC.R:129

weightsAndrews untypeabletimeout

unbound variable (line 109)
unbound: bwAndrews — one of the package’s own names, itself untyped
error detail
name: bwAndrews
gradual mode: timeout
timing: 0.548 s
source
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)
}
R/vcovHAC.R:109

meatHAC untypeable

unbound variable (line 27)
unbound: weightsAndrews — one of the package’s own names, itself untyped
error detail
name: weightsAndrews
timing: 0.605 s
source
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)
}
R/vcovHAC.R:26

vcovHAC.default untypeabletyped

unbound variable (line 10)
unbound: weightsAndrews — one of the package’s own names, itself untyped
error detail
name: weightsAndrews
gradual mode: typed
((x: any, order.by: any?, prewhite: any?, weights: any?, adjust: any?, diagnostics: any?, sandwich: any?, ar.method: any?, data: any?, ...: any) -> any)<>
timing: 0.228 s
source
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)
}
R/vcovHAC.R:9

kernHAC untypeabletyped

unbound variable (line 242)
unbound: bwAndrews — one of the package’s own names, itself untyped
error detail
name: bwAndrews
gradual mode: typed
((x: any, order.by: any?, prewhite: any?, bw: any?, kernel: any?, approx: any?, adjust: any?, diagnostics: any?, sandwich: any?, ar.method: any?, tol: any?, data: any?, verbose: any?, ...: any) -> any)<>
timing: 0.677 s
source
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)
}
R/vcovHAC.R:242

weightsLumley untypeable

unbound variable (line 263)
unbound: isoacf — one of the package’s own names, itself untyped
error detail
name: isoacf
timing: 0.394 s
source
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)
}
R/vcovHAC.R:262

weave skipped

error detail
Invalid_argument("Variable ..._5 is already bound.")
timing: 0.134 s
source
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)
}
R/vcovHAC.R:306

bwNeweyWest untypeable

unbound variable (line 335)
unbound: dQuote — a name the prelude does not declare
error detail
name: dQuote
timing: 4.25 s
source
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)  
}
R/vcovHAC.R:325

NeweyWest untypeable

unbound variable (line 422)
unbound: bwNeweyWest — one of the package’s own names, itself untyped
error detail
name: bwNeweyWest
timing: 0.644 s
source
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)
}
R/vcovHAC.R:417
R/lrvar.R

lrvar untypeabletyped

unbound variable (line 4)
unbound: coredata — a name the prelude does not declare
error detail
name: coredata
gradual mode: typed
((x: any, type: vec?, prewhite: any?, adjust: any?, ...: any) -> any)<>
timing: 0.070 s
source
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)
}
R/lrvar.R:1
R/vcovBS.R

.vcovBSenv typed

env
timing: 0.004 s
source
.vcovBSenv <- new.env()
R/vcovBS.R:1

vcovBS untypeabletyped

unbound variable (line 4)
unbound: UseMethod — a name the prelude does not declare
error detail
name: UseMethod
gradual mode: typed
((x: any, ...: any) -> any)<>
timing: 0.003 s
source
vcovBS <- function(x, ...) {
  UseMethod("vcovBS")
}
R/vcovBS.R:3

vcovBS.default skipped

error detail
Failure("Unsupported argument after an ellipsis.")
timing: 0.025 s
source
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)
}
R/vcovBS.R:7
R/vcovBS.lm.R

vcovBS.lm skipped

error detail
Failure("Unsupported positional argument after a named one.")
timing: 0.019 s
source
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)
}
R/vcovBS.lm.R:1

vcovBS.glm skipped

error detail
Failure("Unsupported argument after an ellipsis.")
timing: 0.059 s
source
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)
}
R/vcovBS.lm.R:169
R/vcovCL.R

matrixinverse untypeabletyped

unbound variable (line 202)
unbound: solve — a name the prelude does not declare
error detail
name: solve
gradual mode: typed
((X: dbl, tol: any?) -> any)<>
timing: 0.224 s
source
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)
}
R/vcovCL.R:200

matrixpower untypeable

unbound variable (line 184)
unbound: isSymmetric — a name the prelude does not declare
error detail
name: isSymmetric
timing: 0.361 s
source
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))
  }
}
R/vcovCL.R:182

meatCL skipped

error detail
Failure("Unsupported argument after an ellipsis.")
timing: 0.098 s
source
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)
}
R/vcovCL.R:17

vcovCL untypeabletyped

unbound variable (line 4)
unbound: meatCL — one of the package’s own names, itself untyped
error detail
name: meatCL
gradual mode: typed
((x: any, cluster: any?, type: any?, sandwich: any?, fix: ff?, ...: any) -> any)<>
timing: 0.066 s
source
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)
}
R/vcovCL.R:1
R/vcovHC.R

vcovHC untypeabletyped

unbound variable (line 2)
unbound: UseMethod — a name the prelude does not declare
error detail
name: UseMethod
gradual mode: typed
((x: any, ...: any) -> any)<>
timing: 0.003 s
source
vcovHC <- function(x, ...) {
  UseMethod("vcovHC")
}
R/vcovHC.R:1

meatHC untypeable

unbound variable (line 23)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
timing: 1.23 s
source
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)
}
R/vcovHC.R:15

vcovHC.default untypeabletyped

unbound variable (line 10)
unbound: meatHC — one of the package’s own names, itself untyped
error detail
name: meatHC
gradual mode: typed
((x: any, type: (vec | null)?, omega: any?, sandwich: any?, ...: any) -> any)<>
timing: 0.110 s
source
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)
}
R/vcovHC.R:5

vcovHC.mlm untypeable

unbound variable (line 124)
unbound: model.matrix — a name the prelude does not declare
error detail
name: model.matrix
timing: 1.29 s
source
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)
}
R/vcovHC.R:113
R/vcovJK.R

vcovJK untypeabletyped

unbound variable (line 2)
unbound: UseMethod — a name the prelude does not declare
error detail
name: UseMethod
gradual mode: typed
((x: any, ...: any) -> any)<>
timing: 0.003 s
source
vcovJK <- function(x, ...) {
  UseMethod("vcovJK")
}
R/vcovJK.R:1

vcovJK.default untypeabletyped

unbound variable (line 7)
unbound: vcovBS — one of the package’s own names, itself untyped
error detail
name: vcovBS
gradual mode: typed
((x: any, cluster: any?, center: (vec | null)?, ...: any) -> any)<>
timing: 0.054 s
source
vcovJK.default <- function(x, cluster = NULL, center = "mean", ...) {
  center <- match.arg(center, c("mean", "estimate"))
  vcovBS(x, cluster = cluster, center = center, type = "jackknife", ...)
}
R/vcovJK.R:5
R/vcovPC.R

meatPC skipped

error detail
File "Rsem/lang/PAst.ml", line 210, characters 14-20: Assertion failed
timing: 0.001 s
source
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)
}
R/vcovPC.R:17

vcovPC untypeabletyped

unbound variable (line 4)
unbound: meatPC — one of the package’s own names, itself untyped
error detail
name: meatPC
gradual mode: typed
((x: any, cluster: any?, order.by: any?, pairwise: any?, sandwich: any?, fix: ff?, ...: any) -> any)<>
timing: 0.086 s
source
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)
}
R/vcovPC.R:1
R/vcovPL.R

meatPL untypeable

unbound variable (line 23)
unbound: estfun — one of the package’s own names, itself untyped
error detail
name: estfun
timing: 5.01 s
source
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)
}
R/vcovPL.R:18

vcovPL untypeabletyped

unbound variable (line 5)
unbound: meatPL — one of the package’s own names, itself untyped
error detail
name: meatPL
gradual mode: typed
((x: any, cluster: any?, order.by: any?, kernel: any?, sandwich: any?, fix: ff?, ...: any) -> any)<>
timing: 0.092 s
source
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)
}
R/vcovPL.R:1