SAS循环宏列表

时间:2018-02-09 20:30:56

标签: sas

您知道如何使用SAS和MACRO迭代列表吗?

%LET table           = item1 item2;/*List of all input*/

/*I try to iterate on the list using a macro*/

%MACRO Main_Extract ;
    array orig[*] &table; 
    do i=1 to dim(orig);
    %put orig[i];
    end; 
%MEND;

%Main_Extract;

1 个答案:

答案 0 :(得分:1)

如果table(项目列表)是数组的变量名,那么您不需要宏。只需使用纯数据步骤代码并使用宏变量列出数组元素。

array orig &table;
do I = 1 to dim(orig);
  put orig[I]=
end;

当宏变量包含空格分隔的项目列表时,通常通过在%scan循环内使用%do解析每个项目来完成宏内部的使用。这很有用的一个例子是为Proc SQL语句生成一系列select子句。

一次性使用解析每个项目

%macro special_sauce (items=);
  %local i item;
  %let i = 1;
  %do %while (%length(%scan(&items,&i)));
    %let item = %scan(&items,&i);

    %put NOTE: code generated for &=item;

    /* ... emit some SAS code or code-snippet involving &item ... */
    &item._squared = &item ** 2;  /* emit data step source statement that presumes item is a variable name that is being squared */

    %let i = %eval(&i+1);
  %end;
%mend;

options mprint;

data want;
  set sashelp.class;
  %special_sauce(items=age height)
run;

如果需要多次使用项目列表,将各个项目存储在本地宏变量中以便于重复使用也很有帮助。

多次使用的项目列表,解析一次并将项目​​放入“宏阵列”中。实际上没有宏数组这样的东西,只是一个可以迭代的数字后缀符号名称的约定。

%macro special_sauce2 (items=);
  %local i item itemCount;
  %let i = 1;
  %do %while (%length(%scan(&items,&i)));
    %let item = %scan(&items,&i);

    %let itemCount = &i;  /* track number of items parsed */ 
    %local item&i;        /* local macro variable name with numeric suffix, sometimes called a macro array */
    %let item&i = &item;  /* save the extracted item */

    %let i = %eval(&i+1);
  %end;

  /* use the items in the 'macro-array' */
  %do i = 1 %to &itemCount;
    %put NOTE: value of macro variable item&i is &&item&i;
    &&item&i.._2 = &&item&i ** 2;
  %end;

  /* use the items in the 'macro-array' */
  %do i = 1 %to &itemCount;
    %put NOTE: Hi again, value of macro variable item&i is &&item&i;
    &&item&i.._3 = &&item&i ** 3;
  %end;
%mend;

options mprint;

data want;
  set sashelp.class;
  %special_sauce2(items=age height)
run;

良好的经验法则,如果你不需要,请不要宏。