Search code examples
sas

Sort variables based on another data set and append data


is there a way in SAS to order columns (variables) of a data set based on the order of another data set? The names are perfectly equal.

And is there also a way to append them (vertically) based on the same column names?

Thank you in advance

 ID        YEAR     DAYS     WORK    DATASET
0001       2020      32      234        1
0002       2019      31      232        1
0003       2015      3       22         1
0004       2003      15      60         1
0005       2021      32      98         1
0006       2000      31      56         1
 DATASET  DAYS    WORK    ID   YEAR
    2      56      23    0001  2010
    2      34      123   0002  2011
    2      432      3    0003  2013
    2      45      543   0004  2022
    2      76      765   0005  2000
    2      43       8    0006  1999

I just need to sort the second data set based on the first and append the second to the first.

Can anyone help me please?


Solution

  • This should work:

    data have1;
        input ID YEAR DAYS WORK DATASET;
        format ID z4.;
        datalines;
    0001 2020 32 234 1
    0002 2019 31 232 1
    0003 2015 3 22 1
    0004 2003 15 60 1
    0005 2021 32 98 1
    0006 2000 31 56 1
    ;
    run;
    
    
    data have2;
        input DATASET DAYS WORK ID YEAR;
        format ID z4.;
        datalines;
    2 56 23 0001 2010
    2 34 123 0002 2011
    2 432 3 0003 2013
    2 45 543 0004 2022
    2 76 765 0005 2000
    2 43 8 0006 1999
    ;
    run;
    

    First we create a new table by copying our first table. Then we just insert into it variables from the second table. No need to change the column order of the original second table.

    proc sql;
        create table want as
            select * 
                from have1
        ;
        insert into want(ID, YEAR, DAYS, WORK, DATASET)
            select ID, YEAR, DAYS, WORK, DATASET
                from have2
        ;
    quit;