【问题标题】:SAS LOOP MACRO LISTSAS 循环宏列表
【发布时间】:2018-02-09 20:30:56
【问题描述】:

您知道如何使用 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;

【问题讨论】:

标签: sas


【解决方案1】:

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

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

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

解析出每个项目的一次使用

%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;

良好的经验法则,如果没有必要,不要使用宏。

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多