0
votes

I created two macro variables in my sas code using the %let option.

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;

the value of the week variable remains 1 even after the loop has executed. Which is the correct way to change the value of Macro variables?

2
I think you need to re-read doco on macro variable resolution, and how SAS tokenises and compiles code. There are a couple of issues, the main one being that you can't do this in open code, but you can do it within the context of a macro by using %do &week=1 %to 53; <do something>; %end;. Another issue (with the example code you've posted) is that you're using i as your iterator variable, but trying to increment a variable called week. - sasfrog
okay..so can i modify macro variables in the do something part of the do loop? - user1946152
Could you provide a bit more detail of what you are doing in the loop. Your current syntax is incorrect, however I'm guessing that you're over complicating the issue (i.e. you want the value of the macro variable week to be the same as the loop variable i). We need to see how you're using these 2 values in the loop. - Longfish
ok i will make an edit to my existing code.So basically i want sum to contain sum of 53 columns in my data set - user1946152
Hmmm okay now you've edited your question I think my initial answer is superseded. Does your data contain 53 columns called _W1_NRX to _w53_NRX? And do you just want to create a variable called sum that adds them up for each row of data? - sasfrog

2 Answers

6
votes

If your week variables are all next to each other in the dataset, you may want to consider a macro-less approach:

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;

If your week variables end with the week number, they do not even need to be next to each other:

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

Clean and easy.

4
votes

Here's a quick example showing how to do this in the context of a macro. Run this and you can see in the log what's happening.

* '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 &sum;
  %end;
%mend;

%put before macro executes, sum is &sum;

%test2

%put after macro executes, sum is now &sum;