Skip to content

Instantly share code, notes, and snippets.

@dholstius
Last active Aug 29, 2015
Embed
What would you like to do?
Optimize alignment of "zoo" objects
optim_lag <- function (z1, z2, merit = cor, max_lag = 120, warn = FALSE) {
require(zoo)
ow <- as.integer(options("warn"))
options(warn = -1 * as.integer(!warn))
on.exit(options(warn = ow))
f <- approxfun(x = index(z2), y = as.numeric(z2))
t_start <- max(start(z1), start(z2))
t_end <- min(end(z1), end(z2))
z1 <- window(z1, start = t_start, end = t_end)
z2 <- window(z2, start = t_start, end = t_end)
x1 <- index(z1)
y1 <- as.numeric(z1)
lag <- optimize(function (d) merit(y1, f(x1 - d)),
interval = max_lag * c(-1, 1),
maximum = TRUE)$maximum
list(lag = lag, zoo = merge(z1, z2 = f(x1 - lag)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment