[R] To calculate the month number between 2 dates

Achim Zeileis Achim.Zeileis at uibk.ac.at
Fri Nov 7 10:08:32 CET 2014


On Fri, 7 Nov 2014, Arnaud Michel wrote:

> Hello
> Can one calculate the month number between two dates
> D1 <- "01/01/2007"  and D2 <- "01/04/2009" ?
> Thank you

One way is through zoo's yearmon class:

R> library("zoo")
R> D1 <- as.yearmon("01/01/2007", format = "%d/%m/%Y")
R> D2 <- as.yearmon("01/04/2009", format = "%d/%m/%Y")
R> D2 - D1
[1] 2.25
R> 12 * (D2 - D1)
[1] 27

Other solutions could go through base R's POSIXlt class, see strptime() 
and difftime().

hth,
Z

>
> -- 
> Michel ARNAUD
> Cirad
>
> ______________________________________________
> 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