获取以年为单位的日期差(浮点数) [英] Get date difference in years (floating point)

查看:72
本文介绍了获取以年为单位的日期差(浮点数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据参考日期和测量日期与源半衰期(以年为单位)之间的差异来更正源活动。说我有

I want to correct source activity based on the difference between reference and measurement date and source half life (measured in years). Say I have

ref_date <- as.Date('06/01/08',format='%d/%m/%y')

和我的 data.frame 具有相同的日期格式,例如

and a column in my data.frame with the same date format, e.g.,

today <- as.Date(Sys.Date(), format='%d/%m/%y')

我可以找到使用 lubridate 软件包

year(today)-year(ref_date)
[1] 5

有没有可以用来获取的函数例如,今天的浮点答案-ref_date = 5.2y?

Is there a function I can use to get a floating point answer today - ref_date = 5.2y, for example?

推荐答案

是的,当然,请在 difftime()中使用as数字:

Yes, of course, use difftime() with an as numeric:

R> as.numeric(difftime(as.Date("2003-04-05"), as.Date("2001-01-01"), 
+                      unit="weeks"))/52.25
[1] 2.2529
R> 

注意,由于$ b有点含糊,我们必须切换到以52.25缩放的周在那里计算$ b的时间-2月29日大约每4年出现一次,但不是每100年出现一次。

Note that we do have to switch to weeks scaled by 52.25 as there is a bit of ambiguity there in terms of counting years---a February 29 comes around every 4 years but not every 100th etc.

所以您必须定义它。 difftime()可处理长达数周的所有时间单位。出于非恒定分子的原因,不能完成数月。

So you have to define that. difftime() handles all time units up to weeks. Months cannot be done for the same reason of the non-constant 'numerator'.

这篇关于获取以年为单位的日期差(浮点数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆