简体   繁体   中英

How to use SAS macro with %DO and %IF

When I ran a macro, the PassengerID_Class had a null value.

I think there is a problem with the sentence below.

%if PassengerID >= &&P&i and PassengerID < &&P&k %then PassengerID_Class = &i. ;

PassengerID is a column containing values from 1 to 891 .

P1 , P2 ,..., Pi are the quantiles.

Below is my code.

%macro do_loop;

DATA _NULL_;
SET PERCENTILES100_Transpose;
call symput("P"||left(_n_),Column1);
RUN;  

Data Groups100;
Set sample;

%do i=2 %to 99;
%Let k = %eval(&i.+1);
%if PassengerID >= &&P&i and PassengerID < &&P&k %then PassengerID_Class = &i. ;
%end;

%mend;

%do_loop;

You cannot test the value of dataset variable with a macro expression. Just use the macro to generate a normal IF statement, the same as you are using the macro to generate the DATA and other SAS statements.

if &&P&i <= PassengerID < &&P&k then PassengerID_Class = &i. ;

But why use macro code at all? Just read the cutoff values into a temporary array.

data Groups100;
  set sample;
  array p[100] _temporary_;
  if _n_=1 then do index=1 by 1 until(eof);
     set PERCENTILES100_Transpose(keep=column1) end=eof;
     p[index]=column1;
  end;
  PassengerID_Class=0;
  do index=2 to 99 until(PassengerID_Class>0);
    if p[index] <= PassengerID < p[index+1] then PassengerID_Class = index ;
  end;
  drop index column1 ;
run;

Note that using the data directly will also avoid loss of precision caused by converting the numbers into text strings to store macro variables.

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