Reverse Order of SAS Data Set

Suppose you want to reverse the order of observations in a SAS data set. Meaning that 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 easily with a simple do loop and the SET Statement with a point= option specified. Below, I will demonstrate a short example of how to achieve this in SAS.

A SAS Example

In the below example, I reverse the example data set SASHELP.CLASS. First, I specify a do loop that reads 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. In this example, starting from the last observation and outputting “Upwards”.


In this example, I demonstrate how to reverse the order of observations in a SAS Data Set. I do so using the Point= Option in the Set Statement of a Data Step. Note, that you should not do this unless it is strictly necessary. From a performance point of view, it is quite costly to read an entire data set one observation at the time with the point= Option.

I also use the Point= Option in the blog post Create a Cartesian Product in SAS.

You can download the entire code from this example here.