Generate Dates with Base R

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.        

要查看或添加评论,请登录

Jorge Miranda, SHRM-SCP的更多文章

  • TLDR; The Coaching Habit

    TLDR; The Coaching Habit

    A big part of my job involves coaching managers in the organization using a 360 feedback assessment. The assessment is…

  • TLDR; "Hybrid Workplace"

    TLDR; "Hybrid Workplace"

    A (Very) Brief Review of Hybrid Workplace: The Insights You Need from Harvard Business Review (HBR Insight Series)…

  • Use SharePoint to Host an R Markdown Web App!

    Use SharePoint to Host an R Markdown Web App!

    To state the obvious, the world has mountains of data. As a people analytics pro, I have seen and used many tools to…

社区洞察

其他会员也浏览了