Monday, March 27, 2017

Hack 4.17 Sorting Variables Within an Observation


SAS Programming Professionals,

Did you know that you can sort the values of variables within an observation into ascending order? 

The SORTN CALL routine allows you to do just that.  Here is an example:

options nodate nonumber;

/* Create the Test data set*/
proc sort in=sashelp.mdv out=work.mdv(keep=origcity shipdate);
      by origcity;
run;

proc transpose data=mdv out=mdvtrans prefix=date;
      by origcity;
      var shipdate;
run;

/* Print the obs with unsorted dates */
proc print data=mdvtrans;
title1 "Dates Not Sorted";
run;

/* Use the SORTN call routine to sort dates */
data sorted_MDV_dates;
set  mdvtrans;

array sortdate{28} date1 - date28;

call sortn (of sortdate(*));

run;

/* Print the obs with sorted dates */
proc print data=sorted_mdv_dates;
title1 "Dates Sorted";
run;

The first part of the program sets up the data set that we will use in the DATA Step that is highlighted in red.  The first steps create a SAS data set with 28 date variable in it.  That data set is output in the first PROC PRINT.  In the DATA Step we use the SORTN to sort the dates (DATE1 – DATE28) into ascending order.  The second PROC PRINT reveals that DATE1 – DATE28 have been sorted into ascending date sequence.  One statement; it’s that simple!

CALL SORTN can be useful in cases where you need to order a series of event dates in an observation for a particular subject id.  Note that its twin function, CALL SORTC, can be used to sort character variables into ascending order within an observation.

Best of luck in all your SAS endeavors!

---MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition:  http://tinyurl.com/z8bzx2e 
Kindle edition: http://tinyurl.com/zypgqa7 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers

No comments:

Post a Comment