Skip to content

Instantly share code, notes, and snippets.

@nataliamd11
Created July 30, 2018 20:10
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nataliamd11/c48078b83c93a2de7502858aa2c9bf61 to your computer and use it in GitHub Desktop.
Function that creates day, month and year columns.
# Function that creates day, month and year columns.
#
OrganizeDateColumns <- function(data.x, ncol.date = 1, orders = "mdyHMS", ncol.day = NULL, ncol.month = NULL, ncol.year = NULL) {
#
require(lubridate)
#
# Organizes dates's columns using lubridate
# If columns with days, months or years are NULL, creates these columns with a
# function inside the function
#
OrganizeDate <- function(ncol.time, fun) {
names.col <- colnames(data.x)
if (is.null(ncol.time) == TRUE) {
if (lubridate::is.POSIXt(data.x[ , ncol.date]) == TRUE) {
col.time <- match.fun(fun)(data.x[ , ncol.date])
data.x[ ,(ncol(data.x) + 1)] <- col.time
colnames(data.x) <- c(names.col, fun)
} else {
data.x[ , ncol.date] <- parse_date_time(x = data.x[ , ncol.date],
orders = orders)
col.time <- match.fun(fun)(data.x[ , ncol.date])
data.x[ ,(ncol(data.x) + 1)] <- col.time
colnames(data.x) <- c(names.col, fun)
}
} else {
col.time <- data.x[ , ncol.time]
colnames(data.x)[ncol.time] <- fun
}
data.x <- data.x
}
#
# Run internal function to data
#
data.x <- OrganizeDate(ncol.time = ncol.day, fun = "day")
data.x <- OrganizeDate(ncol.time = ncol.month, fun = "month")
data.x <- OrganizeDate(ncol.time = ncol.year, fun = "year")
data.x[ , ncol.date] <- as.Date(paste(data.x$year, data.x$month, data.x$day, sep = "-"))
return(data.x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment