使用SAS宏参数的一系列值

时间:2015-10-09 15:17:34

标签: sas

我正在寻找一种方法来为宏参数而不是单个值使用一系列值。我基本上连续几个月(2014年5月到2015年9月)操纵了一系列文件,并且我已经编写了一个宏来利用命名约定。但是,我仍然手动写出使用宏的月份。我这个月已经多次使用了很多不同的文件。有没有办法让参数引用一个值列表,并像数组/执行循环一样通过它们?我已经将%ARRAY作为一种可能性进行了调查,但除非我没有看到它的全部功能,否则它看起来并不像我正在寻找的那样。我在下面附上了此代码的示例。

%MACRO memmonth(monyr=);
proc freq data=work.both_&monyr ;
    table var1/ out=work.mem_&monyr;
run;
data work.mem_&monyr;
    set work.mem_&monyr;
    count_&monyr=count;
run;

%MEND memmonth;


%memmonth(monyr=may14)
%memmonth(monyr=jun14)
%memmonth(monyr=jul14)
%memmonth(monyr=aug14)
%memmonth(monyr=sep14)
%memmonth(monyr=oct14)
%memmonth(monyr=nov14)
%memmonth(monyr=dec14)
%memmonth(monyr=jan15)
%memmonth(monyr=feb15)
%memmonth(monyr=mar15)
%memmonth(monyr=apr15)
%memmonth(monyr=may15)
%memmonth(monyr=jun15)
%memmonth(monyr=jul15)
%memmonth(monyr=aug15)
%memmonth(monyr=sep15)

1 个答案:

答案 0 :(得分:1)

一般情况下,我建议将值列表作为空格分隔列表并在宏中添加循环逻辑。如果空格是值中的有效字符,则使用其他一些分隔符。不要使用逗号作为分隔符,因为这意味着您需要使用宏引用来调用宏。

所以你的基本宏就是这个。

%macro memmonth(monyr);
proc freq data=work.both_&monyr ;
  table var1/ out=work.mem_&monyr (rename=(count=count_&monyr)) ;
run;
%mend memmonth;
%memmonth(may14)
%memmonth(jun14)

您可以将其更改为此。

%macro memmonth(monyrlist);
%local i monyr;
%do i=1 %to %sysfunc(countw(&monyrlist));
  %let monyr=%scan(&monyrlist,&i);
  proc freq data=work.both_&monyr ;
    table var1/ out=work.mem_&monyr (rename=(count=count_&monyr)) ;
  run;
%end;
%mend memmonth;
%memmonth(may14 jun14)

如果你总是希望在一个间隔内处理所有月份,那么你可以直接传入间隔的开始和结束月份。

%macro memmonth(start,end);
%local i monyr;
%do i=0 %to %sysfunc(intck(month,"01&start"d,"01&end"d));
  %let monyr=%sysfunc(intnx(month,"01&start"d,&i),monyy5.);
  proc freq data=work.both_&monyr ;
    table var1/ out=work.mem_&monyr (rename=(count=count_&monyr)) ;
  run;
%end;
%mend memmonth;
%memmonth(may14,sep15)

如果您有源列表,无论是文本文件还是数据集,您都可以使用简单的数据步骤来生成宏调用。因此,如果您有一个带有变量MONYR的输入数据集,那么您的驱动程序将如下所示:

data _null_;
   set mylist ;
   call execute(cats('%nrstr(memmonth)(',MONYR,')'));
run;

如果源是具有名称的文件,则将SET语句替换为适当的INFILE和INPUT语句。如果源是目录名,那么请查看许多SAS方法之一,将目录中文件的名称读入数据集,并使用它来驱动宏调用生成。