Posted by : Netbloggy Friday, September 18, 2015

SAS offers a lot of flexible functions in reading and writing Dates. Let's explore some of it.

Problem 1: 

Compute a person's age in years

Input:

001 10/21/1950 05122003 08/10/65 23Dec2005

002 01/01/1960 11122009 09/13/02 02Jan1960

Solution:

data A15001.A01_Four_Dates;
infile '/folders/myfolders/iSAS/a01_dates.txt';
input @1 Subject $3.
@5 DOB mmddyy10.
@16 VisitDate mmddyy8.
@26 TwoDigit mmddyy8.
@34 LastDate date9.;
 
format DOB VisitDate LastDate mmddyy10.
  TwoDigit date9.;
run;
 
proc print data=A15001.A01_Four_Dates; 
*format DOB VisitDate LastDate mmddyy10.
  TwoDigit date9.;
run;
*yearcutoff is to cutoff all those previous years;*options yearcutoff=1910; 
data A15001.A01_Ages;
 set A15001.A01_Four_Dates;
 age1 = yrdif(DOB,VisitDate,'Actual'); *as of visitdate;
 age2 = yrdif(DOB,'05SEP2015'd,'Actual');*as of this date - date constant; 
 age3 = yrdif(DOB,today(),'Actual'); *as of today;
run;
 
title "Listing of Age";
Proc print data=A15001.A01_Ages;
 id subject;
 var DOB VisitDate age1 age2 age3; 
run; 

Output:
Learning:


  • Reading date with date informat and write it in the dataset in a different date format
  • Understanding the global option YEARCUTOFF to change the default yearcutoff to handle two-digit years
  • Calculating Age (difference of years) with yrdif function
  • Understanding Date constant - '19SEP2015'd
  • Understanding today() function that outputs today's date
Problem 2:

Use mdy() & other such function to combine & extract month,week and day from a date and also calculate intervals between two dates.

Solution:

*extracting weekday, day, month and year;
 
data A01_Extract;
 set A15001.A01_Four_Dates;
 day = weekday(DOB);
 dayofmonth= day(DOB);
 Month = month(DOB);
 year = year(DOB);
run;
 
proc print data=A01_Extract noobs;
 var DOB Day -- Year;
run;  
 
*creating date from month,day,year values;
 
data A01_MDY_Ex;
 set A01_Extract;
 dob_date = mdy(month,dayofmonth,year);
 format dob_date mmddyy10.;
run;
 
proc print data=A01_MDY_Ex;
var dob_date;
run;
 
*INTCK to calculate interval bw two dates;
 
data A01_Interval;
 set A01_MDY_Ex;
 yr_interval = INTCK('year',dob_date,today());
 qtr_interval = INTCK('qtr',dob_date,today());
run;
 
proc print data=A01_Interval;;
var dob_date yr_interval qtr_interval;
run; 
 
Output:
Learning:


  • Understanding date functions like mdy(), day(), month(), year()
  • Using INTCK function to calculate intervals (qtr, year, day, week) between two dates


Download the code from here

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Popular Post

Blogger templates

Total Pageviews

Powered by Blogger.

- Copyright © nulldata -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -