Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - lubridate - Convert Period into numeric counting months

Tags:

r

lubridate

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.

like image 671
Eric Lecoutre Avatar asked Mar 24 '17 08:03

Eric Lecoutre


1 Answers

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"
like image 156
Ishan Juneja Avatar answered Nov 12 '22 21:11

Ishan Juneja