Search code examples
loopssassas-macro

SAS: use dynamic macro variable in loop in macro program


I want to achieve the same as:

data train_Sex(keep=Name Sex) train_Age(keep=Name Age) train_Height(keep=Name Height) train_Weight(keep=Name Height);
    set sashelp.class;
run;

using a macro program with a list of variables. As far as I went:

* Build macro program;
%macro build_sets(var_list);
    %let nwords = %sysfunc(countw(&var_list));

    %do i=1 %to &nwords;
        call symput("variable",  %scan(&var_list, i));

        data train_&variable(keep=Name &variable);
            set sashelp.class;
        run;

    %end;
%mend;

* Run it;
%let var_list = Sex Age Height Weight;
%build_sets(&var_list);

But I am lacking the knowledge how can I dynamically change the "variable" var.

Thanks!


similar questions:

1.SAS dynamically declaring macro variable 2. Using a dynamic macro variable in a call symput statement 3. Dynamic macro variable access SAS


Solution

  • you were close. below thing should work for you. call symput is part of datastep is used to create macrovariable from dvariables and hence the issue.

     %macro build_sets(var_list);
    ;
    
    %do i=1 %to  %sysfunc(countw(&var_list));
        %let variable=  %scan(&var_list, &i));
    
        data train_&variable(keep=Name &variable);
            set sashelp.class;
        run;
    
    %end;
    %mend;
    
     * Run it;
    %let var_list = Sex Age Height Weight;
    %build_sets(&var_list);