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')
and a column in my data.frame
with the same date format, e.g.,
today <- as.Date(Sys.Date(), format='%d/%m/%y')
I can find the number of years between these dates using the lubridate
package
year(today)-year(ref_date) [1] 5
Is there a function I can use to get a floating point answer today - ref_date
= 5.2y, for example?
Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.
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>
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.
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'.
The lubridate package contains a built-in function, time_length, which can help perform this task.
time_length(difftime(as.Date("2003-04-05"), as.Date("2001-01-01")), "years") [1] 2.257534 time_length(difftime(as.Date("2017-03-01"), as.Date("2012-03-01")),"years") [1] 5.00274
Documentation for the lubridate package can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With