M. Beausoleil M. Beausoleil - 3 months ago 8
R Question

How to calculate a decimal month in R in a particular year?

If I have a date, say

"2014-05-13"
and I want to calculate the month in decimal, I would do this:

5 + 13/31 = 5.419355


How would it be possible in R to take a vector of dates and turn in it into a "month decimal" vector?

For example:

dates = c("2010-01-24", "2013-04-08", "2014-03-05", "2013-03-08", "2014-02-14",
          "2004-01-28", "2006-02-21", "2013-03-28", "2013-04-01", "2006-02-14",
          "2006-01-28", "2014-01-19", "2012-03-12", "2014-01-30", "2005-04-17")

library(lubridate)
month(dates) + day(dates)/31


As you can see, it would be wrong to put "31" as the diviser since the number of days differ depending on the month, and sometimes year (leap years).

So what would be the best solution?

Answer

You can use monthDaysfunction from Hmisc package

> require(Hmisc)
> library(lubridate)
> month(dates) + day(dates)/monthDays(dates)
 [1] 1.774194 4.266667 3.161290 3.258065 2.500000 1.903226 2.750000 3.903226 4.033333
[10] 2.500000 1.903226 1.612903 3.387097 1.967742 4.566667
Comments