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

Ana Patricia Martins
2006-04-19T13:44:47Z

Hi,

I tried to apply the function you developed to my data file, which had to be
created as follows:

date1<-sub('    -  -
','',paste(substring(ie[,],257,260),substring(ie[,],255,256),substring(ie[,]
,253,254),sep="-"))

Your functions works well only in example #1 but when I applied a
"cycle"
(if clause) doesn't work (example #2 and #3).

Example #1:
a35641<-num.months (dados$date1[35641],dados$date2[35641])
[1] 68

Example #2:
mes1<-with(dados,ifelse(date1!="    -  -
",num.months(date1,date2),""))
>Error in fromchar(x) : character string is not in a standard unambiguous
format

Example #3:
mes<-c(rep("NA",length(dados$date1)))
for (i in 1:m){
    if (dados$date1[i]!="    -  -  ")
mes[i]<-num.months(dados$date1[i],dados$date2[i])}


Do you think you can solve this problem?

Thanks in advance for your cooperation.
Best regards,
Ana Patricia Martins
-------------------------------------------
Servi?o M?todos Estat?sticos
Departamento de Metodologia Estat?stica
INE - Portugal
Telef:  218 426 100 - Ext: 3210
E-mail: ana.pmartins at ine.pt

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Smith, Phil
Sent: segunda-feira, 17 de Abril de 2006 21:06
To: r-help at stat.math.ethz.ch
Subject: [R] Function for computing the difference between 2 dates in months

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

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!