[R] Need help on date calculation

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jul 10 21:07:18 CEST 2010


On Sat, Jul 10, 2010 at 3:17 PM, Bogaso Christofer
<bogaso.christofer at gmail.com> 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?

as.integer truncates so if its slightly below 2, as is the case here,
you will get 1 as you observe so try any of these:

# 1
as.integer(round(nm))

# 2 - just about any small number will do
as.integer(nm + 0.001)

Also see:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f



More information about the R-help mailing list