R - lubridate - 如何将时间段转换为数值型的月份计数

12

请考虑以下内容:

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

现在我正在尝试用月份做类似的事情:

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

这是 lubridate 的一个 bug 吗?还是我做错/漏掉了什么?

注意:我看到(旧的)评论:Have lubridate subtraction return only a numeric value,所以我猜我也可以使用 difftime 来解决问题,但我想坚持使用 lubridate。


2
假设这不是期望的行为,我怀疑 seconds_to_unitperiod_to_seconds 可能值得探索。 - Roman Luštrik
1个回答

21

不要使用as.numeric(),尝试使用lubridate包中的time_length()函数:

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"

2
谢谢Ishan!我甚至没有注意到lubridate中有这个函数——要知道的太多了! - Eric Lecoutre
这个函数不在lubridate的备忘单上,而且让我非常吃惊。 https://rawgit.com/rstudio/cheatsheets/main/lubridate.pdf - Eduardo Zanette

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接