R/na_extrap.R

Defines functions na_extrap

#' @export
na_extrap <- function(X, index_x, index_y, data, x_d, x_pq) {
    x_models <- vector(mode = "list", length = NCOL(X))
    for (i in 1:NCOL(X)) {
        if (anyNA(X[[i]][setdiff(index_x, index_y)])) {
            X_ts_all <- ts(X[[i]])
            X_ts_forecast <- ts(X[[i]][setdiff(index_x, index_y)])
            missng_all <- is.na(X_ts_all)
            missng_forecast <- is.na(X_ts_forecast)
            tryCatch(
                expr = x_models[[i]] <- forecast::forecast(
                    object = forecast::Arima(
                        y = X_ts_all,
                        order = c(x_pq[[i]][1], x_d[i], x_pq[[i]][2]),
                        method = c("ML")
                    ),
                    h = length(setdiff(index_x, index_y))
                ),
                error = function(e) {
                    cat(
                        "Message: missing values in", i,
                        "were not extrapolated ARIMA => extrapolated ARIMA (auto).\n"
                    )
                }
            )
            if (is.null(x_models[[i]])) {
                tryCatch(
                    expr = x_models[[i]] <- forecast::forecast(
                        object = forecast::auto.arima(X[[i]]),
                        h = length(setdiff(index_x, index_y))
                    ),
                    error = function(e) {
                        cat(
                            "Message: missing values in", i,
                            "were not extrapolated => extrapolated mean.\n"
                        )
                    }
                )
            }
            if (is.null(x_models[[i]])) {
                X[[i]][missng_all] <- mean(X[[i]], na.rm = TRUE)
                return(X)
            } else {
                X[[i]][missng_all] <- x_models[[i]]$mean[missng_forecast]
                return(X)
            }
        }
    }
}
faganok/scenario documentation built on Nov. 28, 2017, 4:06 p.m.