GoodluckR
GoodluckR

Reputation: 23

SAS macro nested loop

I would like to build a logistic model containing two predictors. One from set all_indeps1, and one from all_indeps2. I run below macro, however, it only run model with the first variable from all_indeps1, and all variables from all_indeps2. How should I fix the macro so that I could have all possible combinations of two variables from two sets?

Also, I would like to only output the p-values for each predictors from the logistic model, any ideas?

Many Thanks!

%macro trivariate(all_indeps1, all_indeps2);
%let k = 1;
%let l = 1;
%let indep1 = %scan(&all_indeps1, &k);
%let indep2 = %scan(&all_indeps2, &l);

    %do %while("&indep1" NE "");
        %do %while ("&indep2" NE "");
    title "independent variable is &Indep1 and &Indep2";
    proc logistic data = A descending;
        model Y = &indep1 &indep2;
    run;
        %let l = %eval(&l + 1);
        %let indep2 = %scan(&all_indeps2, &l);
        %end;
    %let k = %eval(&k + 1);
    %let indep1 = %scan(&all_indeps1, &k );

    %end;

%mend;

Upvotes: 1

Views: 5130

Answers (2)

Joe
Joe

Reputation: 63434

I wouldn't code this as a macro loop at all, but instead set it up so your macro is just the inner bit, and call the macro n1*n2 times.

Say you have two datasets, indep1 and indep2, each of which contains a single column with one variable name per row. Then if you had a macro:

%macro trivariate(indep1,indep2);
   title "independent variable is &Indep1 and &Indep2";
    proc logistic data = A descending;
        model Y = &indep1 &indep2;
    run;
%mend trivariate;

proc sql;
 select cats('%trivariate(',indep1.var,',',indep2.var,')') into :trivarlist
  separated by ' ' 
  from indep1, indep2;
quit;

&trivarlist.;

It's almost always easier to control repetition outside of the macro language than inside of it, excepting very simple cases; and it's a better programming style as it makes for more portable and reusable code.

Upvotes: 1

DomPazz
DomPazz

Reputation: 12465

This is really 2 questions.

1.Nothing jumps out at me as wrong with your macro. Try options mprint mlogic; to see more of what is going on behind the scenes.

I would personally code this as

%macro trivariate(all_indeps1, all_indeps2);
%let n1 = %sysfunc(countw(&all_indeps1));
%let n2 = %sysfunc(countw(&all_indeps2));
%do i=1 to &n1;
   %let indep1 = %scan(&all_indeps1,&i);
   %do j=1 %to &n2;
      %let indep2 = %scan(&all_indeps2,&i);

      STUFF
   %end
%end;
%mend;

2.Choosing only 1 output from a PROC. Use ods trace on; your procedure, and then ods trace off; That will print the table names that are put to output destination.

You can then use ods select <list of table names>; your procedure, and then ods select default; That will tell the Output Delivery System (ODS) to only print the tables you ask for and then reset to default output. (This table is probably ParameterEstimates in your case)

Upvotes: 1

Related Questions