[R] Function for computing the difference between 2 dates in months

Smith, Phil
2006-04-17T20:05:51Z

Folks:

With the help of David L. Reiner, I've developed a function that
computes the number of months between 2 dates, x and y.


num.months	<-	function ( x , y )
{
	x	<-	as.Date( x )
	y	<-	as.Date( y )
	seeq	<-	seq(from=x , to=y , by="months")
	ans	<-	length( seeq  ) - 1
	if ( max( seeq) > y ) ans <- ans -1
	ans
}

To ease your reading this function, I've left out some data cleaning
issues, and it is assumed that x <= y  and that x and y were output from
as.date function (note the lower case "d" in as.date). The postscript
below provides 2 examples.

Anyone who wishes to comment or recommend a more accurate (or correct!)
method is welcome.

Best regards,
Phil Smith
Centers for Disease Control and Prevention

Example #1:


> x<-c( "2004-02-28" )
> y<-c( "2004-04-27" )
> num.months ( x , y )
[1] 1
>


Example #2:

> x<-c( "2004-01-31" )
> y<-c( "2004-04-22" )
> num.months ( x , y )
[1] 2