[R] difftime in years

Jim Lemon drjimlemon at gmail.com
Fri Aug 5 01:34:25 CEST 2016


Hi Thomas,
Be aware that if you are attempting to calculate "birthday age", it is
probably better to do it like this:

bdage<-function(dob,now) {
 dobbits<-as.numeric(unlist(strsplit(dob,"/")))
 nowbits<-as.numeric(unlist(strsplit(now,"/")))
 return(nowbits[3]-dobbits[3]-
  (nowbits[2]<dobbits[2] || (nowbits[2]==dobbits[2] && nowbits[1]<dobbits[1])))
}
bdage("20/09/1945","5/8/2016")

You can also do this with date objects, just add the appropriate
format arguments.

Jim


Jim

On Fri, Aug 5, 2016 at 6:35 AM, William Dunlap via R-help
<r-help at r-project.org> wrote:
> difftime objects do not accept 'years' as a value for 'units', so you have
> to change it to numeric.
>
>     as.numeric(age_days, units="days") / 365.242
>
> The units="days" is not needed since you specified it in the call
> to difftime, but it needs to be in one of those places.
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
> On Thu, Aug 4, 2016 at 11:05 AM, Thomas Subia via R-help <
> r-help at r-project.org> wrote:
>
>> Colleagues,
>>
>> age_days <- difftime(Date,DOM,units="days")
>> date_vals$age_yrs <-  age_days/365.242
>>
>> I'm trying to calculate the number of years between DOM and Date.
>> The output reads
>>
>>              DOM               Date                 age_yrs
>> 1 2005-04-04   2015-05-13           10.10563 days
>>
>> How does one not output days?
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/
>> posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list