Created
December 26, 2021 19:05
-
-
Save abmathewks/9112b7807a0f9bc1f94cf52af91efca2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AddEngineeredDates <- function(AGG_TS_DATA, | |
DATE_COLUMN = "date", | |
DEBUG = TRUE){ | |
if(DEBUG) message("AddEngineeredDates: Function Initialized \n") | |
if(!data.table::is.data.table(AGG_TS_DATA)){ | |
stop("AddEngineeredDates: The input data is not a data table \n") | |
} | |
if(!class(AGG_TS_DATA[[DATE_COLUMN]]) %chin% c("Date")) { | |
stop("AddEngineeredDates: The date column is not saved in date format \n") | |
} | |
FUNCTION_OUTPUT <- list() | |
FUNCTION_OUTPUT[["DATE_COLUMN"]] <- DATE_COLUMN | |
FUNCTION_OUTPUT[["ORIGINAL_DATA"]] <- AGG_TS_DATA | |
AGG_TS_DATA[, date_ymd := lubridate::ymd(get(DATE_COLUMN))] | |
AGG_TS_DATA[, date_year := data.table::year(date_ymd)] | |
AGG_TS_DATA[, date_quarter := data.table::quarter(date_ymd)] | |
AGG_TS_DATA[, date_month := data.table::month(date_ymd)] | |
AGG_TS_DATA[, date_day := lubridate::day(date_ymd)] | |
AGG_TS_DATA[, date_dayofweekname := factor(lubridate::wday(date_ymd, label=TRUE), ordered = FALSE)] | |
AGG_TS_DATA[, is_weekend := fifelse(weekdays(get(DATE_COLUMN)) %in% c("Saturday","Sunday"), 1, 0)] | |
AGG_TS_DATA[, date_ymd_week := lubridate::floor_date(date_ymd, unit = "week")] | |
AGG_TS_DATA[, date_ymd_month := lubridate::floor_date(date_ymd, unit = "month")] | |
if(DEBUG) message("AddEngineeredDates: Collecting final output \n") | |
FUNCTION_OUTPUT[["FINAL_DATA"]] <- AGG_TS_DATA | |
if(!is.null(AGG_TS_DATA) || !nrow(AGG_TS_DATA) == 0){ | |
if(DEBUG) message("AddEngineeredDates: Data acquisition completed \n") | |
return(FUNCTION_OUTPUT) | |
} else { | |
stop("AddEngineeredDates: Function returned an empty data set \n") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment