[R] Turn dates into age
Marc Schwartz
marc_schwartz at me.com
Sun Nov 8 21:24:00 CET 2009
As Jim has noted, if the dates you have below are an 'end date', you
need to define the time0 or start date for each to calculate the
intervals. On the other hand, are the dates you have below the start
dates and you need to calculate the time to today? In the latter case,
see ?Sys.Date to get the current system date from your computer.
Generically speaking you can use the following:
(EndDate - StartDate) / 365.25
where EndDate and StartDate are of class Date. This will give you the
time interval in years plus any fraction.
You can then use round() which will give you a whole year with typical
rounding up or down to the nearest whole integer. You can use floor(),
which will give you the nearest whole integer less than the result or
basically a round down result. Keep in mind that the above calculation
does not honor a calendar year, but is an approximation.
If you want to calculate age in years as we typically think of it
using the calendar, you can use the following, where DOB is the Date
of Birth (Start Date) and Date2 is the End Date:
# Calculate Age in Years
# DOB: Class Date
# Date2: Class Date
Calc_Age <- function(DOB, Date2)
{
if (length(DOB) != length(Date2))
stop("length(DOB) != length(Date2)")
if (!inherits(DOB, "Date") | !inherits(Date2, "Date"))
stop("Both DOB and Date2 must be Date class objects")
start <- as.POSIXlt(DOB)
end <- as.POSIXlt(Date2)
Age <- end$year - start$year
ifelse((end$mon < start$mon) |
((end$mon == start$mon) & (end$mday < start$mday)),
Age - 1, Age)
}
HTH,
Marc Schwartz
On Nov 8, 2009, at 1:30 PM, jim holtman wrote:
> What is the frame of reference to determine the age? Check out
> 'difftime'.
>
> On Sun, Nov 8, 2009 at 1:50 PM, frenchcr <frenchcr at btinternet.com>
> wrote:
>>
>> Ive got a big column of dates (also some fields dont have a date so
>> they have
>> NA instead),
>> that i have converted into date format as so...
>>
>>
>> dates<-as.character(data[,"date_commissioned"]); # converted dates to
>> characters
>> dates[1:10]
>> [1] "19910101" "19860101" "19910101" "19860101" "19910101" "19910101"
>> "19910101" "19910101" "19910101" "19910101"
>>
>> dateObs <- as.Date(dates,format="%Y%m%d")
>> dateObs[1:10]
>> [1] "1991-01-01" "1986-01-01" "1991-01-01" "1986-01-01" "1991-01-01"
>> "1991-01-01" "1991-01-01" "1991-01-01" "1991-01-01" "1991-01-01"
>>
>>
>>
>> Now i need to turn the dates into AGE, how do i do it? Im not
>> worried about
>> fractions of years, whole years would do.
More information about the R-help
mailing list