Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
add_engineered_dates <- function(dat, date_col = "created_date"){
assertthat::assert_that(any(class(dat) == "data.table"),
msg = "the data is not stored in a data.table...please investigate")
if(!class(dat[,get(date_col)]) %in% c("POSIXct","POSIXt")){
message("changing date class type")
dat[, c(date_col) := lubridate::ymd_hms(get(date_col))][]
}
# if featured data cols not present, add date features
if(!all(c(paste0(date_col, "_Year", sep=""),
paste0(date_col, "_YearMonth", sep=""),
paste0(date_col, "_YearWeek", sep=""),
paste0(date_col, "_Day", sep=""),
paste0(date_col, "_MonthWeek", sep=""),
paste0(date_col, "_YearMonthWeek", sep=""),
paste0(date_col, "_Date", sep=""),
paste0(date_col, "_Time", sep="")) %in% colnames(dat))){
message("engineered date columns not present...adding them now")
dat[, paste0(date_col, "_Year") := lubridate::year(get(date_col))]
dat[, paste0(date_col, "_YearMonth", sep="") := substr(get(date_col)[!is.na(get(date_col))],1,7)]
dat[, paste0(date_col, "_YearWeek", sep="") := paste(substr(get(date_col)[!is.na(get(date_col))],1,4),
lubridate::week(get(date_col)[!is.na(get(date_col))]), sep="-")]
dat[, paste0(date_col, "_Day") := weekdays(get(date_col)[!is.na(get(date_col))])]
dat[, paste0(date_col, "_MonthWeek") := ifelse( ceiling(mday(get(date_col))/7)==5, 4,
ceiling(mday(get(date_col))/7) )]
dat[, paste0(date_col, "_YrMonthWeek") := paste(substr(get(date_col)[!is.na(get(date_col))],1,4),
substr(get(date_col)[!is.na(get(date_col))],6,7),
ifelse( ceiling(mday(get(date_col))/7)==5, 4,
ceiling(mday(get(date_col))/7) ), sep="-")]
dat[, paste0(date_col, "_Date") := substr(get(date_col)[!is.na(get(date_col))],9,10)]
dat[, paste0(date_col, "_Time") := hms::hms(second(created_at),
minute(created_at),
hour(created_at))]
}
message("date check completed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.