Skip to content

Instantly share code, notes, and snippets.

@pbnelson
Created November 16, 2018 15:53
Show Gist options
  • Save pbnelson/0a75e0e37dc694ebf919048a9703c885 to your computer and use it in GitHub Desktop.
Save pbnelson/0a75e0e37dc694ebf919048a9703c885 to your computer and use it in GitHub Desktop.
Elapsed Months in `R`
# A simple function to compute elapsed months between start date and end date
elapsed_months <- function(end_date, start_date) {
ed <- as.POSIXlt(end_date)
sd <- as.POSIXlt(start_date)
12 * (ed$year - sd$year) + (ed$mon - sd$mon)
}
#
# Example:
#
# >Sys.time()
# [1] "2014-10-29 15:45:44 CDT"
# >elapsed_months(Sys.time(), as.Date("2012-07-15"))
# [1] 27
# >elapsed_months("2002-06-30", c("2002-03-31", "2002-04-30", "2002-05-31"))
# [1] 3 2 1
# To me it makes sense to think about this problem as simply subtracting two dates, and since minuend − subtrahend = # difference (wikipedia), I put the later date first in the parameter list.
# Note that it works fine for dates preceeding 1900 despite those dates having internal representations of year as negative, thanks to the rules for subtracting negative numbers...
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment