[R] question about difference in date objects

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 2 12:45:00 CET 2009


Since months have different lengths the difference in months is not
well defined but lets define it as the difference between the first of
the month of two dates. In that case we can use as.yearmon of the zoo
package.  It converts to year/months, dropping days, using an internal
representation of year + 0 for Jan, year + 1/12 for Feb, year + 2/12
for Mar, etc.  so differencing and multiplying by 12 gives the number
of months:

> # test data
> d1 <- Sys.Date(); d1
[1] "2009-11-02"
> d2 <- d1 - 100; d2
[1] "2009-07-25"

> library(zoo)
> 12 * (as.yearmon(d1) - as.yearmon(d2))
[1] 4


On Mon, Nov 2, 2009 at 6:29 AM, Phil Smith
<philipsmith at alumni.albany.edu> wrote:
> Hi R Community:
>
> I want to take the difference in two dates:
>
> dt2 - dt1.
>
> But, I want the answer in months between those 2 dates.
>
> Can you advise me?
>
> Please respond to: pzs6 at cdc.gov
>
> Thank you!
> Phil Smith
> Centers for Disease Control and Prevention
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list