简体   繁体   中英

SAS: Non-sequential do loop within a data step

I would like to be able to execute a do loop for a non-sequential set of values. The way I have written this code runs a new data step for each value - so therefore the end product is a data table with a column added for the final value of the do loop only. What I want is for the the values in the varlst to loop through the if/then statements - thereby adding multiple columns to the table - without executing a new data step each time (which only results in adding one final column to the table).

INPUT DATA

DATA have;
INPUT id order Q3 Q5 Q6 Q50 Q75 Q102;
DATALINES;
 1  1  2 0  7 2 2 0
 1  2  3 0  5 5 3 0
 3  1  6 1  7 2 7 1
 3  2  6 0  7 5 7 0
 6  1  3 1  4 7 7 2
 6  2  5 2  7 7 7 1
 7  1  3 5  6 5 3 0
 7  2  4 1  7 5 2 1
 9  1  4 1  6 5 6 1
 9  2  1 3  5 7 5 0
; 
run;

/********/

 %macro test;
    %let varlst=2 3 5 6 50 75 102 /*more values*/;
    %do i=1 %to %sysfunc(countw(&varlst));
    %let value=%scan(&varlst,&i);
    data want;
    set have;
    by id order;
    if Q&value ne lag(Q&value) and not first.id then do; 
            Q&value.Equal = 0; 
                end;
        if Q&value=lag(Q&value) and not first.id then do;
        Q&value.Equal = 1;
                end;
                %end;
       run;
    %mend;
    %test;

/**********/ OUTPUT

id  order   Q3  Q5  Q6  Q50  Q75 Q102 Q102Equal
1   1       2    0   7   2    2   0     .
1   2       3    0   5   5    3   0     1
3   1       6    1   7   2    7   1     .
3   2       6    0   7   5    7   0     0
6   1       3    1   4   7    7   2     .
6   2       5    2   7   7    7   1     0
7   1       3    5   6   5    3   0     .
7   2       4    1   7   5    2   1     0
9   1       4    1   6   5    6   1     .
9   2       1    3   5   7    5   0     0

Why don't you try using PROC COMPARE ?

data have ;
  input id  order   Q3  Q5  Q6  Q50  Q75 Q102;
cards;
1   1       2    0   7   2    2   0     .
1   2       3    0   5   5    3   0     1
3   1       6    1   7   2    7   1     .
3   2       6    0   7   5    7   0     0
6   1       3    1   4   7    7   2     .
6   2       5    2   7   7    7   1     0
7   1       3    5   6   5    3   0     .
7   2       4    1   7   5    2   1     0
9   1       4    1   6   5    6   1     .
9   2       1    3   5   7    5   0     0
;;;;

proc compare
   data=have(where=(order=1))
   compare=have(where=(order=2)) 
   outdiff out=want 
;
  id id ;
  var q: ;
run;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM