Reverse Order of SAS Data Set

Suppose for some reason you want to reverse a SAS data set. Meaning you want the last observation in the data set to be the first, the second last to be number 2 and so on. This can be done fairly easy with a simple do loop and the SET Statement with a point= option specified.

A SAS Example

In the below example, I reverse the example data set SASHELP.CLASS. The first thing I do is to specify a do loop reading from the number of observations in SASHELP.CLASS to 1. This works because in the do loop, I use the Set Statement along with the NOBS= option to initialize a variable telling me the number of observations in the input data set. I can use the NOBS variable prior to the SET Statement because the NOBS variable is initialized during compilation of the data set. Not execution.

data reverse_class;
do i=nobs to 1 by -1;
	set sashelp.class nobs=nobs point=i;

Finally, I use the POINT= option to point to exactly the variable I am looping over, starting from the last observation and outputting “Upwards”.


You can download the entire code from this example here.