在SAS中修改宏变量的值

时间:2013-07-15 09:58:33

标签: sas

我使用%let 选项在我的sas代码中创建了两个宏变量。

data sasdata1.dataone;
set sasdata1.dataone ;
%let week=1;
%let sum=0;
do i=1 to 53;
%let sum= _W&week._NRX + &sum.;
week=&week+1;
end;
drop i;
week=&week;
sum=&sum.;
run;

即使循环执行后,周变量的值仍为1。哪个是更改宏变量值的正确方法?

2 个答案:

答案 0 :(得分:6)

如果您的周变量在数据集中彼此相邻,您可能需要考虑无宏方法:

data sasdata1.dataone;
    set sasdata1.dataone;
    sum = sum(of _W1_NRX--_W53_NRX); *double dash means that the columns are next to each other with _W1_NRX as first and _W53_NRX as last;
run;

如果您的周变量以周数结尾,则它们甚至不需要彼此相邻:

data sasdata1.dataone;
    set sasdata1.dataone;
    sum = sum(of _W1-_W53); *single dash implies that the suffix is numerically increasing;
run;

清洁简单。

答案 1 :(得分:4)

这是一个快速示例,展示了如何在宏的上下文中执行此操作。运行此命令,您可以在日志中看到发生了什么。

* 'week' is in scope within the macro only
  and iterates because of %do loop (no need
  to explicitly increment it ;
%macro test1;
  %do week=1 %to 10;
    %put &week;
  %end;
%mend;

%test1

* sum has global scope ;
%let sum=0;
* 'week' acts as per test1 above, but we
  explicitly manipulate 'sum' within each iteration ;
%macro test2;
  %do week=1 %to 10;
    %let sum=%eval(&sum+&week);
    %put in macro: week is &week, sum is now ∑
  %end;
%mend;

%put before macro executes, sum is ∑

%test2

%put after macro executes, sum is now ∑