Monday, February 15, 2016

Hack 2.1 Calculating a Person’s Age in Years

SAS Programming Professionals,

Did you know that you can easily calculate a person’s age in years?

The optional AGE argument for the YRDIF function allows you to calculate a person’s age in years.  The AGE argument takes all of the leap years into account as it determines the number of years between a birthdate and another date.  Here is an example:

data mikeage;

bdate = "27APR1975"D;

CurrentAge = int(yrdif(bdate, today(), 'AGE'));

put "Michael's current aqe is:  " CurrentAge;

run;

In the example, we obtain the subject’s birthdate in the BDATE variable.  Then, we use the YRDIF function with the AGE argument to calculate how old the subject is as of today.  The log looks like this:

1    data mikeage;
2
3    bdate = "27APR1975"D;
4
5    CurrentAge = int(yrdif(bdate, today(), 'AGE'));
6
7    put "Michael's current aqe is:  " CurrentAge;
8
9    run;

Michael's current age is:  40

Note that we used the INT function to return an integer representation of the subject’s age.  Not doing so would have resulted in an age of 40.78630137 which, I am sure you will agree, is not quite so meaningful.

Best of luck in all your SAS endeavors!

----MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)

Excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers

I plan to post each and every one of the hacks in the book to social media on a weekly basis.  Please pass them along to colleagues who you know would benefit.