At first I thought there was a bug in SAS! Later I realized it was a problem with one of my "if" conditions. It was actually an issue of me not realizing that '01JAN1960' has a value of 0.
Let's say I want to calculate the age for some records, given a birthdate field that is usually missing.
Here is a sample data set:
data sample;
id='1';birthdate='01JAN1970'd; output;
id='2';birthdate='02JAN1970'd;output;
id='3';birthdate=.;output;
id='4';birthdate='01JAN1960'd;output;
run;
/*In a second data step, I calculate the ages:*/
data ages;
set sample;
if birthdate then age = floor((intck('month',birthdate,today()) - (day(today()) < day(birthdate))) / 12);
run;
Do you see the problem? The intention is to calculate the age only if the birthdate is not missing. However, if the birthdate is on January 1, 1960, then the value is 0, which is a numeric false. The "if" resolves to false, so the "then" part of the statement doesn't get executed.
The "if" statement should read as follows:
if birthdate ne . then age = floor((intck('month',birthdate,today()) - (day(today()) < day(birthdate))) / 12);
It was one of those gotcha moments.
if not missing(birthdate) then age = intck('year',birthdate,today(),'c');
if not missing(birthdate) then age = intck('year',birthdate,today(),'c');
Might want to look at the YRDIF function with the Floor function if you don't need a decimal part of a year.
I'm slightly curious as to why SAS doesn't create an "age" function, since it's something that is often computed. The "YRDIF" function doesn't immediately come to mind.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.