Search code examples
saslevels

SAS: how to change the order of a categorical variable


To make it simple let's say I have a dataset consiting of four names: Anna, Bobby , Casper, Christine. The column name is just 'Names'.

I want to sort it in this order: Bobby, Anna, Casper, Christine. I cant use 'proc sort' with 'asc/desc' here. Because it's ordered randomly I need to type in the order manually.

Can I somehow include it the following proc sort statement?

 Proc Sort
  data = dataset; order by Names;
run;

Solution

  • The answer from @Joe is the best way due to being scalable and the ability to read in formats from a dataset using CNTLIN. I just thought I'd post an alternative solution, using proc sql. The version SAS uses enables you to create a custom order on the fly by adding an order by statement along with a case statement. Effectively this creates an extra column in memory which is used to sort on, but the column is not output.

    This is a useful method when the number of items to sort on is relatively small.

    proc sql;
    create table want 
    as select *
    from have
    order by case names
                when 'Bobby' then 1
                when 'Anna' then 2
                when 'Casper' then 3
                when 'Christine' then 4
            end;
    quit;