R/internal.R

Defines functions parse_number seconds_to_period tic.log bizseq_internal yj_transform estimate_yj_lambda loess_fitted na_linear abind_two abind_internal split_array toc tic tic.clearlog number str_to_title transpose pmap map_depth map_chr map_df pmap_dbl map_dbl map2 map as_mapper `%||%`

## Internal replacements for previously imported helper packages.
`%||%` <- function(x, y) if (is.null(x)) y else x
as_mapper <- function(.f, ...) {
  if (is.function(.f)) return(.f)
  if (inherits(.f, "formula")) {
    env <- environment(.f); body <- .f[[length(.f)]]
    body <- parse(text = gsub("\\.\\.(\\d+)", ".lambda_dots[[\\1]]", gsub("\\.x", ".lambda_dots[[1]]", gsub("\\.y", ".lambda_dots[[2]]", deparse(body)))))[[1]]
    return(function(...) { .lambda_dots <- list(...); eval(body, envir = environment()) })
  }
  stop(".f must be a function or formula")
}
map <- function(.x, .f, ...) lapply(.x, as_mapper(.f), ...)
map2 <- function(.x, .y, .f, ...) Map(function(x, y) as_mapper(.f)(x, y, ...), .x, .y)
map_dbl <- function(.x, .f, ...) vapply(.x, as_mapper(.f), numeric(1), ...)
pmap_dbl <- function(.l, .f, ...) vapply(pmap(.l, .f, ...), as.numeric, numeric(1))
map_df <- function(.x, .f, ...) do.call(rbind, lapply(.x, as_mapper(.f), ...))
map_chr <- function(.x, .f, ...) vapply(.x, as_mapper(.f), character(1), ...)
map_depth <- function(.x, depth, .f, current = 1) {
  if (current > depth) return(as_mapper(.f)(.x))
  lapply(.x, map_depth, depth = depth, .f = .f, current = current + 1)
}
pmap <- function(.l, .f, ...) {
  f <- as_mapper(.f)
  if (inherits(.f, "formula")) {
    n <- length(.l[[1]])
    return(lapply(seq_len(n), function(i) do.call(f, c(list(...), lapply(.l, `[[`, i)))))
  }
  do.call(Map, c(list(f), .l))
}
transpose <- function(.l) if (!length(.l)) list() else Map(c, .l[[1]], .l[[2]])
str_to_title <- function(x) paste0(toupper(substring(x, 1, 1)), substring(x, 2))
number <- function(x, ...) format(x, big.mark = ",", trim = TRUE, ...)

tic.clearlog <- function() invisible(NULL)
tic <- function(name = "time") assign(".lambdaTS_tic", proc.time()[["elapsed"]], envir = parent.frame())
toc <- function(log = TRUE) {
  start <- get0(".lambdaTS_tic", envir = parent.frame(), ifnotfound = proc.time()[["elapsed"]])
  elapsed <- proc.time()[["elapsed"]] - start
  if (isTRUE(log)) message("elapsed time: ", round(elapsed, 3), " seconds")
  invisible(elapsed)
}

split_array <- function(x, along, drop = TRUE) {
  d <- dim(x); n <- d[along]
  lapply(seq_len(n), function(i) {
    idx <- rep(list(TRUE), length(d)); idx[[along]] <- i
    out <- do.call(`[`, c(list(x), idx, list(drop = drop)))
    out
  })
}

abind_internal <- function(..., along = 1) {
  if (along < 0) { xs <- list(...); if (length(xs) == 1L && is.list(xs[[1]])) xs <- xs[[1]]; return(array(unlist(xs), dim = c(dim(xs[[1]]), length(xs)))) }
  xs <- list(...); if (length(xs) == 1L && is.list(xs[[1]])) xs <- xs[[1]]
  maxd <- max(c(length(dim(xs[[1]])), along))
  xs <- lapply(xs, function(x) { d <- dim(x); if (length(d) < maxd) dim(x) <- c(d, rep(1, maxd - length(d))); x })
  d <- dim(xs[[1]])
  if (along == maxd) return(array(unlist(xs), dim = c(d[-along], sum(vapply(xs, function(x) dim(x)[along], integer(1))))))
  out <- xs[[1]]
  for (x in xs[-1]) out <- abind_two(out, x, along, d)
  out
}
abind <- abind_internal
abind_two <- function(a, b, along, d = dim(a)) {
  if (along == 1) return(rbind(a, b))
  if (along == 2) return(cbind(a, b))
  da <- dim(a); db <- dim(b); dim(a) <- c(prod(da[seq_len(along - 1)]), da[along], prod(da[-seq_len(along)]))
  dim(b) <- c(prod(db[seq_len(along - 1)]), db[along], prod(db[-seq_len(along)]))
  z <- array(c(a, b), dim = c(dim(a)[1], dim(a)[2] + dim(b)[2], dim(a)[3]))
  dim(z) <- c(d[-(along)], dim(z)[2]); aperm(z, c(seq_along(d)[-along], along))
}

na_linear <- function(x) {
  if (!anyNA(x)) return(x)
  ok <- is.finite(x); if (sum(ok) < 2) return(replace(x, !ok, 0))
  approx(which(ok), x[ok], seq_along(x), rule = 2)$y
}

loess_fitted <- function(x, y) {
  fit <- stats::loess(y ~ x, control = stats::loess.control(surface = "direct"))
  as.numeric(stats::predict(fit, data.frame(x = x)))
}

estimate_yj_lambda <- function(x) {
  ## Profile likelihood-free robust grid estimate: select the lambda that
  ## minimizes skewness after transformation, avoiding car::powerTransform.
  skew <- function(z) { m <- mean(z); s <- stats::sd(z); if (!is.finite(s) || s == 0) 0 else mean((z - m)^3) / s^3 }
  grid <- seq(-2, 2, length.out = 81)
  score <- vapply(grid, function(l) abs(skew(yj_transform(x, l))), numeric(1))
  grid[which.min(score)]
}
yj_transform <- function(x, lambda) {
  out <- numeric(length(x)); pos <- x >= 0
  if (lambda == 0) out[pos] <- log1p(x[pos]) else out[pos] <- ((x[pos] + 1)^lambda - 1) / lambda
  if (lambda == 2) out[!pos] <- -log1p(-x[!pos]) else out[!pos] <- -(((-x[!pos] + 1)^(2 - lambda) - 1) / (2 - lambda))
  dim(out) <- dim(x); out
}

bizseq_internal <- function(start, n, days_off = NULL) {
  dates <- seq.Date(as.Date(start) + 1, by = "day", length.out = max(2 * n + 14, n))
  if (!is.null(days_off)) dates <- dates[!tolower(weekdays(dates)) %in% tolower(days_off)]
  head(dates, n)
}

tic.log <- function(...) proc.time()[["elapsed"]]
seconds_to_period <- function(seconds) structure(seconds, class = "difftime", units = "secs")
parse_number <- function(x) as.numeric(gsub("[^0-9.+-]", "", x))

Try the lambdaTS package in your browser

Any scripts or data that you put into this service are public.

lambdaTS documentation built on Sept. 7, 2026, 9:08 a.m.