dorayin
dorayin

Reputation: 127

loop a list of variables in SAS

I have a dataset with 10+ dependent variables and several categorical variables as independent variables. I'm plan to use proc sgplot and proc mixed functions to do analysis. However, putting all variables one by one in the same function will be really time consuming. I'm pretty new to SAS, is there a way to create a loop with dependent variables and put them into the function. Something like:

%let var_list= read math science english spanish
proc mixed data=mydata;
model var_list= gender age race/ solution;
random int/subject=School;
run;

Thank you!

Upvotes: 1

Views: 6076

Answers (2)

jmr
jmr

Reputation: 29

I would do something like this. This creates a loop around your proc mixed -call. I didn't take a look at the proc mixed -specification, but that may not work as described in your example.

The loop works however, and loops through whatever you put in the place of the proc mixed -call and the loop is dynamically sized based on the number of elements in the dependent variable list.

First define some macro variables.

%let y_var_list = read math science english spanish;
%let x_var_list = gender age race;
%let mydata = my_student_data;

Then define the macro that does the looping.

%macro do_analysis(my_data=, y_variables=, x_variables=);

%* this checks the nr of variables in y_var_list;
%let len_var_list = %eval(%sysfunc(count(&y_variables., %quote( )))+1);

%do _i=1 %to &len_var_list;
    %let y_var = %scan(&y_variables, &_i);
    %put &y_var; %* just printing out the macrovar to be sure it works;

    %* model specification;
    proc mixed data=&my_data.; %* data given as parameter in the macro call. proc mixed probably needs some output options too, to work;
    model &y_var = &x_variables/ solution; %* independent vars as a macro parameter;
    random int/subject=School;
    run;

%end;

%mend do_analysis;

Last but not least, remember to call your macro with the given variable lists and dataset specifications. Hope this helps!

%do_analysis(my_data=&mydata, y_variables=&y_var_list, x_variables=&x_var_list);

Upvotes: 1

Tom
Tom

Reputation: 51621

SAS has a macro language you can use to generate code. But for this problem you might want to just restructure your data so that you can use BY processing instead.

data tall ;
  set mydata ;
  array var_list read math science english spanish ;
  length varname $32 value 8;
  do _n_=1 to dim(var_list);
    varname=vname(var_list(_n_));
    value = var_list(_n_);
    output;
  end;
run;
proc sort data=tall;
  by varname ;
run;

Now you can process each value of VARNAME (ie 'read','math', ....) as separate analyses with one PROC MIXED call.

proc mixed data=tall;
  by varname;
  model value = gender age race/ solution;
  random int/subject=School;
run;

Upvotes: 2

Related Questions