Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate ages in R

Tags:

r

I have two data frames in R. One frame has a persons year of birth:

YEAR
/1931
/1924

and then another column shows a more recent time.

RECENT
09/08/2005
11/08/2005

What I want to do is subtract the years so that I can calculate their age in number of years, however I am not sure how to approach this. Any help please?

like image 367
Brian Avatar asked Aug 31 '10 16:08

Brian


People also ask

How do you calculate age in a database?

We can find the age of a person from their date of birth by using this formula: SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),'DATE_OF_BIRTH')), '%Y') + 0 AS age; In the above formula, we are first finding the difference between the current date (NOW()) and the date of birth (in YYYY-MM-DD) using the DATEDIFF() function.

How do you evaluate age?

Allergy blood tests are used to help find out if you have an allergy. There are two general types of allergy blood tests: A total IgE test is used to measure the total amount of IgE antibodies in your blood. A specific IgE test measures how much IgE your body makes in response to a single allergen.

How is age algorithm calculated?

The first formula that many of us learn is rather appealing in its simplicity: AGE = int((NOW - DOB)/365.25); First determine the number of days from DOB to NOW, then divide by the number of days in a year.


1 Answers

The following function takes a vectors of Date objects and calculates the ages, correctly accounting for leap years. Seems to be a simpler solution than any of the other answers.

age = function(from, to) {
  from_lt = as.POSIXlt(from)
  to_lt = as.POSIXlt(to)

  age = to_lt$year - from_lt$year

  ifelse(to_lt$mon < from_lt$mon |
         (to_lt$mon == from_lt$mon & to_lt$mday < from_lt$mday),
         age - 1, age)
}
like image 167
Jim Avatar answered Sep 21 '22 08:09

Jim