In this post, I will provide small examples of how to create permutations in the SAS Data Step. I will show how to generate random permutations and all permutations of the values in a list. In the examples, I will use temporary arrays and permute them accordingly with the Ranperm, Ranperk and Allperm Routines.

Random Permutations in Data Step

First, let us see how to create random permutations of values in an array in SAS. In the example below, I use the Ranperm Call Routine. The Ranperm Routine randomly permutes all the input values. In the example, I create a temporary array r and create ten random permutations of the elements in the array. Run the code and check the log to the the permuted elements.

data _null_;
   array r {5} _temporary_ (1 : 5);
   s = 123;
   do _N_ = 1 to 10;
      call ranperm(s, of r [*]);
      t = catq('d', '|', of r [*]);
      put t;
   end;
run;

Next, let us see an example of how to permute some of the elements in the array. The Call Ranperk Routine permutes the values of the arguments and returns a random permutation of k out of n values. See the code example below. Here, I create the same SAS array as above. However, I do not permute all elements. Instead, I permute one of the elements. In effect, the first element of the array is switched with a random other element in the array.

data _null_;
   array r {5} _temporary_ (1 : 5);
   s = 123;
   do _N_ = 1 to 10;
      call ranperk(s, 1, of r [*]);
      t = catq('d', '|', of r [*]);
      put t;
   end;
run;

All Permutations in Data Step

As a final example, let us consider how to generate all possible permutations of the elements in the SAS array. In the code example below, I use the Allperm Routine. the examples above are simple in the sense that if we want 10 random permutations, we simply call the routines 10 times. However, in this case we first have to determine how many different ways the elements in the array can be permuted. We can do this with the Fact Function. The Fact Function returns the factorial of the input number. Consequently, if we want to compute all permutations of an array with five elements, I loop from 1 to fact(5) like below. Run the code and check the log. All permutations of the array with the elements 1, 2, 3, 4 and 5 are now printed.

data _null_;
   array r {5} _temporary_ (1 : 5);
   do _N_ = 1 to fact (5);
      call allperm(_N_, of r [*]);
      t = catq('d', '|', of r [*]);
      put t;
   end;
run;

Summary

In this post, I demonstrate small example of how to create permutations of values in the SAS data step. I provide examples using the three call routines Ranperm, Ranperk and Allperm. I highly encourage you to browse the documentation of the routines and play around with the code examples to get the grasp of them.

Also, read the related posts Investigating the PROC PLAN in SAS by Example and Generate All Possible Sums in SAS.

You can download the entire code from this post here.