Monday, December 5, 2016

Hack 4.4 Creating SAS Date Variables with the MDY Function

SAS Programming Professionals,

Did you know that you can create a SAS date variable from a set of month, date, and year variables?

The MDY function creates a SAS date value from month, day, and year values.  It can be helpful when you process data where the unfortunate decision was made to collect month, day, and year in separate variables.  Here  is an example of the MDY function:

data newdate;

format birthdate worddate.;

birth_day = 27;
birth_month = 4;
birth_year = 1975;

birthdate = mdy(birth_month, birth_day, birth_year);

yearsold = year(today()) - year(birthdate);

run;

proc print noobs;
run;

In the example, we employ the MDY function to create a SAS date variable, BIRTHDATE, from separate birth_month, birth_day, and birth_year variables.  Then, we use BIRTHDATE to compute the subject’s age.

A derivative of this simple technique can be used in cases where you get the month and year of a date, but for privacy’s sake, you do not get the day.  You can hardcode a given day value—say 15 because it is the middle of most months—and create a reasonable date that you can use in calculations.  For example, consider the DATA step above without the day variable:

data newdate;

format birthdate worddate.;

birth_month = 4;
birth_year = 1975;

birthdate = mdy(birth_month, 15, birth_year);

yearsold = year(today()) - year(birthdate);

run;

In this example, we hard-coded 15 in the MDY function so that we could compute a valid date for BIRTHDATE.  We could have just as easily used a 1 or a 28 to signify the first day of the month, or a day near the end of the month.  Which is the better way to go?  It is your manager’s sage choice, of course!

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
http://www.amazon.com/Michael-A.-Raithel/e/B001K8GG90/ref=ntt_dp_epwbk_0

No comments:

Post a Comment