[R] Time difference in months? (difftime, units)
Gabor Grothendieck
ggrothendieck at myway.com
Wed Nov 17 17:16:53 CET 2004
Andy Bunn <abunn <at> whrc.org> writes:
:
: Is there a way to calculate the number of months between dates?
:
: StartDate <- strptime("01 March 1950", "%d %B %Y")
: EventDates <- strptime(c("01 April 1955", "01 July 1980"), "%d %B %Y")
: difftime(EventDates, StartDate)
:
: So, there are 61 months between 01 March 1950 and 01 April 1955. There are
: 364 months between 01 March 1950 and 01 July 1980. What I want is for there
: to be a "months" argument to units in difftime. Anybody have a bright idea?
: Is there a better way to approach this than difftime?
1. There are an average of 365.25/12 days per month so the following
expression gives the number of months between d1 and d2:
# test data
d1 <- as.Date("01 March 1950", "%d %B %Y")
d2 <- as.Date(c("01 April 1955", "01 July 1980"), "%d %B %Y")
# calculation
round((d2 - d1)/(365.25/12))
2. Another possibility is to get the length of seq.Dates like this:
as.Date.numeric <- function(x) structure(floor(x+.001), class = "Date")
sapply(d2, function(d2) length(seq(d1, as.Date(d2), by = "month")))-1
More information about the R-help
mailing list