Eric Lecoutre
Eric Lecoutre

Reputation: 1481

R - lubridate - Convert Period into numeric counting months

Consider following:

library(lubridate)
period1 = weeks(2)
as.numeric(period1, "weeks")
> 2   # as expected 

Now I am trying to do similar with months:

period2= months(6)
as.numeric(period2, "months")
as.numeric(period2, "weeks")
>  26.08929  # OK
as.numeric(period2,"months")
>  0.04166667  # Not OK?

Is this a bug in lubridate? Or something wrong I am doing/missing?

Note: I have seen (old) remark Have lubridate subtraction return only a numeric value, so I guess I may also use workaround to use difftime but I would like to stick to lubridate.

Upvotes: 13

Views: 6318

Answers (1)

Ishan Juneja
Ishan Juneja

Reputation: 421

Instead of using as.numeric() try time_length() from lubridate package:

period2= months(6)
time_length(period2,unit="days")
#182.6
time_length(period2,unit="weeks")
#26.09
time_length(period2,unit="months")
#6.004
class(time_length(period2,unit="months"))
#"numeric"

Upvotes: 22

Related Questions