SAS Loop through list of macro variable

喜欢而已 提交于 2021-02-10 07:15:02

问题


First off, I'm new so I apologize if this is not a good question. I searched but did not find something similar. I'm not sure my approach is correct so any assistance would be appreciated.

I'm working on a data set for a school that has semesters for example 2017SP is Spring of 2017, 2017SU is Summer of 2017 and so on.

I have the following program where I set up a Macro Variable at the top and then use it to pull out the term from various libraries and data sets. Note that I have several data steps and just need to run the entire program over 5 times.

%let STC_TERM=2017SU;

Data Step; set (library that has data on all terms); if STC_TERM = "&STC_TERM"; *other things I want to do* run; I have several other similar data steps in my program that finally give me the output data I want.

Now I need to create a data set with five semesters worth of data just appended to each other.

Instead of running my code 5 times and just changing "%let STC_TERM=2017SU;" to "%let STC_TERM=2016SU;" for each year I want I was hoping there was someway of providing my list of 5 terms and have SAS loop through each of the 5 terms and append the results together.

The five terms are (2017SU, 2016SU, 2015SU, 2014SU, 2013SU).

Is there a way to give this list to my program and have it perform all the data steps first on 2017SU then on the next semester and so on and append the resulting 5 sets together?

I can't just put in all the terms of interest in the data step because some of the terms have repeating data between them and need to be dealt with separately. Trying to put all the terms in the data step has not worked for me before so I want to keep them separate by running the entire program separately for each semester.


回答1:


Just wrap your existing code in a macro and have the macro iterate over the list of values. See this other question for another example: Simple iteration through array with proc sql in SAS

If you want to accumulate the results into a single table then add a PROC APPEND step to the end of your code.

%macro do_all(termlist);
  %local i stc_term ;
  %do i=1 %to %sysfunc(countw(&termlist,%str( )));
    %let STC_TERM=%scan(&termlist,&i,%str( ));

data step1;
  set have ;
  where STC_TERM = "&STC_TERM";
  * ... other things I want to do in this step ... ;
run;
...
data step_last;
   set stepX;
   ...
run;

proc append base=all data=step_last force ;
run;

  %end;
%mend do_all;

Then call it with the list of values.

%do_all(2017SU 2016SU 2015SU 2014SU 2013SU)


来源:https://stackoverflow.com/questions/44288284/sas-loop-through-list-of-macro-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!