Sal
Sal

Reputation: 117

Extract month over several years with lubridate

Extracting month in lubridate is straightforward: month(some_date), and this gives 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5...

But what if I need to determine month number over several years to get 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16... ? Is there a way to reach this in lubridate (or with R base) ? Thank you

I tried this

Day <- c('2015/01/01', '2015/03/01', '2015/07/25', '2016/03/05', '2016/11/28')
Day <- date(Day)
Month <- Day - min(Day)
Month <- ((Month/ddays(1))/30.41)+1
Month <- trunc(Month)

but it obviously gives a poor approximation of the month (1 2 7 15 23 --March 1st, 2015 being considered as belonging to month #2).

Upvotes: 2

Views: 356

Answers (1)

Jaap
Jaap

Reputation: 83215

What you can do is substract the first year from the year of the date and multiply that by 12 and add that to the output of month(Day). This will add 0 for the first year, 12 for the second year and so on.

Using:

month(Day) + (year(Day) - min(year(Day)))*12

gives:

[1]  1  3  7 15 23

In base R you could do it as follows (as also suggested by @DavidArenburg):

mnths <- as.POSIXlt(Day)
mnths$mon + 1 + (mnths$year - min(mnths$year)) * 12

Upvotes: 4

Related Questions