学習メモ(主に統計学とSAS)

学習したことのメモを記載しています。

【SAS】(検証)%if %then %doを先に書くか後で書くか

%if %then %doを使用して条件分岐させた際に想定と異なる結果になった気がしたので検証した。

 

/* データ作成 */

data input;
  input usubjid $ flg1 flg2 flg3;
cards;
A 1 . .
B . 1 .
C . . 1
;
run;

 

/* ① if then doをdata stepの中に書いた場合 */

%macro makeds_(no_=);
data ds1_&no_.;
  %if &no_.=1 %then %do;
    set input(in=n1 where=(flg1=1))
        input(in=n2 where=(flg2=1))
        ;
     nflg=whichn(1, n1, n2);
  %end;

  %if &no_.=2 %then %do;
    set input(in=n1 where=(flg1=1))
        input(in=n2 where=(flg2=1))
        input(in=n3 where=(flg3=1))
        ;
     nflg=whichn(1, n1, n2, n3);
  %end;
run;

%mend makeds_;

%makeds_(no_=1);
%makeds_(no_=2);

 

■ds1_1

■ds1_2

 

/* ② if then doをdata stepの外に書いた場合 */

%macro makeds2_(no_=);
%if &no_.=1 %then %do;
data ds2_1;
    set input(in=n1 where=(flg1=1))
        input(in=n2 where=(flg2=1))
        ;
     nflg=whichn(1, n1, n2);
run;
%end;

%if &no_.=2 %then %do;
data ds2_2;
    set input(in=n1 where=(flg1=1))
        input(in=n2 where=(flg2=1))
        input(in=n3 where=(flg3=1))
        ;
     nflg=whichn(1, n1, n2, n3);
run;
%end;

%mend makeds2_;

%makeds2_(no_=1);
%makeds2_(no_=2);

 

■ds2_1

 

■ds2_2

 

/* 比較 */

proc compare base=ds1_1 compare=ds2_1; run; /* 一致する */

 

proc compare base=ds1_2 compare=ds2_2; run; /* 一致する */

 

■検証結果

どちらの書き方でも結果は変わらなかった。

①の書き方だと、一部nflgが欠測になる場合があったのだが、勘違いだったのかもしれない。