Search code examples
sas

Sort a dataset based on the order of another


I have two datasets that look like this:

      PATID         Mean           
      0001          234
      0004          230
      0007          237
      0008          239
      0010          231
      ....          ...        

and a second one that looks like this:

      PATID         std           
      0010          4.1
      0008          5.9
      0007          6.8
      0001          1.1
      0004          12.9
      ....          ...  

Is there a way to sort the second dataset by PATID with the order of PATID of the first? Although not all are shown for simplicity, the two datasets have the same PATIDs although in a different order.

Thank you in advance


Solution

  • I am guessing PATID is a character variable given the leading 0's.
    A simple proc sort should do the trick

    data have;
    infile datalines;
    input patid $4. std :8.;
    datalines;
    0010 4.1
    0008 5.9
    0007 6.8
    0001 1.1
    0004 12.9
    ;
    
    proc sort data=have out=want; by patid; quit;
    
    patid std
    0001  1.1
    0004  12.9
    0007  6.8
    0008  5.9
    0010  4.1
    

    Should dataset one not be sorted in an ascending order, you could create the sequence order and left join

    data have1;
    infile datalines;
    input patid $4. mean :8.;
    datalines;
    0001 234
    0007 237
    0004 230
    0010 231
    0008 239
    ;
    
    data have2;
    infile datalines;
    input patid $4. std :8.;
    datalines;
    0010 4.1
    0008 5.9
    0007 6.8
    0001 1.1
    0004 12.9
    ;
    
    data have1_view / view=have1_view;
    set have1;
    seq=_n_;
    run;
    
    proc sql;
        create table want as
        select t1.patid, t2.std
        from have1_view t1 left join have2 t2
        on t1.patid = t2.patid
        order by seq
        ;
    quit;
    
    patid std
    0001  1.1
    0007  6.8
    0004  12.9
    0010  4.1
    0008  5.9