R/set_lag.R

Defines functions set_lag

#' @export
set_lag <- function(x, z = NULL, diff = 0, lag_max = 3, alpha = 0.1) {
    x <- c(na.omit(unlist(x)))
    if (!is.null(z)) {
        z1 <- x
        z2 <- z
    }
    if (diff != 0) {
        x <- diff(x = as.ts(x), differences = diff)
    }
    
    acf <- acf(
        x = x,
        lag.max = lag_max,
        type = "correlation",
        plot = FALSE
    )$acf[-1, , 1]
    acf <- abs(acf)
    
    pacf <- acf(
        x = x,
        lag.max = lag_max,
        type = "partial",
        plot = FALSE
    )$acf[, , 1]
    pacf <- abs(pacf)
    
    if (!is.null(z)) {
        z <- c(na.omit(unlist(z)))
        ccf <- ccf(
            x = z1,
            y = z2,
            lag.max = lag_max,
            type = "correlation",
            plot = FALSE
        )$acf[, , 1]
        ccf <- abs(rev(ccf[1:floor(length(ccf)/2)]))
    }
    max_cor_lag <- NULL
    
    if (!is.na(max(pacf))) {
        if (max(pacf) >= alpha) {
            max_cor_lag[1] <- which.max(pacf)
        } else {
            max_cor_lag[1] <- 0
        }
    } else {
        max_cor_lag[1] <- 0
    }
    
    if (!is.na(max(acf))) {
        if (max(acf) >= alpha) {
            max_cor_lag[2] <- which.max(acf)
        } else {
            max_cor_lag[2] <- 0
        }
    } else {
        max_cor_lag[2] <- 0
    }
    
    if (!is.null(z)) {
        if (!is.na(max(ccf))) {
            if (max(ccf) >= alpha) {
                max_cor_lag[3] <- which.max(ccf)
            }  else {
                max_cor_lag[3] <- 1
            }
        } else {
            max_cor_lag[3] <- 1
        }
        names(max_cor_lag) <- c("PACF", "ACF", "CCF")
    } else {
        names(max_cor_lag) <- c("PACF", "ACF")
    }
    return(max_cor_lag)
}
faganok/scenario documentation built on Nov. 28, 2017, 4:06 p.m.