Created
July 30, 2018 20:10
Star
You must be signed in to star a gist
Function that creates day, month and year columns.
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
# 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