julieth
julieth

Reputation: 442

loop through variables to create interaction terms

I seek to loop through variables (can be contained in a macro variable or a data set) to create a macro variable with interaction terms that I can use in a regression. Here is an example.

Let’s say the original variables are in a macro variable.

%let predictors = age sex bmi;

I seek to loop through these variables and create a macro variable that I can use in a regression.

In the first iteration, we have age. I seek to create:

% interactions = age sex bmi sex*age bmi*age

Fit a regression.

Then use sex in the next iteration.

% interactions = age sex bmi age*sex bmi*sex;

And so on. Thanks!

Upvotes: 0

Views: 737

Answers (2)

Tom
Tom

Reputation: 51611

Note really sure how you are using this, but a simple %do loop should handle your request.

%macro test(predictors);
%local n i j ;
%let n=%sysfunc(countw(&predictors));
%do i=1 %to &n;
  %let interactions=&predictors;
  %do j=1 %to &n;
    %if &i^=&j %then %let interactions=
       &interactions %scan(&predictors,&i)*%scan(&predictors,&j)
    ;
  %end;
  %put &=i &=interactions;
%end;
%mend ;
%test(age sex bmi);

Which produces this list to the log.

I=1 INTERACTIONS=age sex bmi age*sex age*bmi
I=2 INTERACTIONS=age sex bmi sex*age sex*bmi
I=3 INTERACTIONS=age sex bmi bmi*age bmi*sex

Upvotes: 0

data _null_
data _null_

Reputation: 9109

The model statement of many SAS PROCs supports a syntax for that. The pipe is all crossings while @2 limits the interactions to 2 way. Leave off the @ for all.

proc glm data=sashelp.class;
   class sex;
   model age=sex|height|weight@2;
   run;
   quit;

enter image description here

Upvotes: 1

Related Questions