[R] Need help on date calculation

David Winsemius dwinsemius at comcast.net
Sat Jul 10 21:17:21 CEST 2010


On Jul 10, 2010, at 3:17 PM, Bogaso Christofer wrote:

> Hi all, please see my code:
>
> library(zoo)
>> a <- as.yearmon("March-2010", "%B-%Y")
>
>> b <- as.yearmon("May-2010", "%B-%Y")
>>
>> nn <- (b-a)*12   # number of months in between them
>> nn
> [1] 2
>
>> as.integer(nn)
> [1] 1
>
> What is the correct way to find the number of months between "a" and  
> "b",
> still retaining the INTEGER property?

Not sure what you mean by _retaining_ the integer property since items  
of the yearmon class are numeric and are NOT integer. You just  
multiplied 2/12 by 12 and got a result that was very slightly less  
than 2. There was a thread yesterday where I offered a possible  
solution to a request that trunc be slightly less "literal" and allow  
(2/12)*12 to be "truncated" to 2.

trnc3 <- function(x) trunc(x+sign(x)* .Machine$double.eps^0.5)
 > (b-a)*12 == 2
[1] FALSE
 > trnc3((b-a)*12) == 2
[1] TRUE

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list