Generate Dates with Base R
Jorge Miranda, SHRM-SCP
Data Scientist specializing in integrating and making sense of HR data.
In celebration of R Studio changing its name to Posit, I thought I'd share some old-school base R code.
I love using base R to do things because the code is easier to maintain compared to code written with dependencies. As much as I love lubridate and the tidyverse, I love maintainable code even more. Here's a task I need so often that I created a helper function for myself.
I often need to create a list of dates that I use to perform some function on. This function specializes in producing the last given number of dates based on certain parameters.
last_dates = function( start_date = Sys.Date(),
? ? ? ? ? ? ? ? ? ? ? ?dates_back = NULL,?# how many dates to return
? ? ? ? ? ? ? ? ? ? ? ?by = "month", # by month, quarter, year?
? ? ? ? ? ? ? ? ? ? ? ?round_start = TRUE, # round down the start date?
? ? ? ? ? ? ? ? ? ? ? ?round_units = "months"?# if rounding, to what unit?
) {
??
? if ( methods::missingArg( dates_back ) ) { stop("Missing argument dates_back") }
??
? if ( round_start ) {?
? ? start_date = trunc( as.POSIXlt( start_date ), units = round_units )?
? ? start_date = as.Date( start_date )
? }
??
? by = paste("-1", by)
??
? date_vec = seq(?
? ? start_date,?
? ? by = by,?
? ? length.out = dates_back
? )
??
? return( date_vec )
}
last_dates( dates_back = 6 )?# produces a vector of 6 dates, each the 1st of the month starting with the current month.