R获取年份差异(浮点数) [英] R get date difference in years (floating point)

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

问题描述

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

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

I can find the number of years between these dates using the lubridate package

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()数字:

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> 

请注意,我们必须切换到52.25周的周数,因为有一点歧义
在这里计算年数 - 一个二月二十九日每四年一次,但不是每一百次等。

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'.

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

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