Jonsi Billups
Jonsi Billups

Reputation: 153

SAS SymputX and Symget Function

I try to construct Table 2 by writing below SAS code but what I get is the Table 1. I could not figure out what I missed. Help very appreciated Thank you.

     &counter = 4

     data new;set set1;
     total = 0;
     a = 1;
     do i = 1 to &counter;
       call symputX('a',a);
       total = total + Tem_&a.;
       a = symget('a')+1;
       call symputX('a',a);
     end;
     run;



      Table 1
      ID    Amt Tem_1   Tem_2   Tem_3   Tem_4   total
       4    500    1        4       5    900    3600
       5    200   50      100     200      0       0
       9    50    40        0       0      0       0
      10    500   70      100     250      0       0



     Table 2
     ID Amt Tem_1   Tem_2   Tem_3   Tem_4   total
      4 500    1        4       5    900     910
      5 200   50      100     200      0     350
      9 50    40        0       0      0      40
     10 500   70      100     250      0     420

Upvotes: 0

Views: 384

Answers (1)

Joe
Joe

Reputation: 63424

You cannot use SYMPUT and SYMGET that way, unfortunately. While you can use them to store/retrieve macro variable values, you cannot change the code sent to the compiler after execution.

Basically, SAS has to figure out the machine code for what it's supposed to do on every iteration of the data step loop before it looks at any data (this is called compiling). So the problem is, you can't define tem_&a. and expect to be allowed to change what _&a. is during execution, because it would change what that machine code needs to do, and SAS couldn't prepare for that sufficiently.

So, what you wrote the &a. would be resolved when the program compiled, and whatever value &a. had before your data step woudl be what tem_&a. would turn into. Presumably the first time you ran this it errored (&a. does not resolve and then an error about & being illegal in variable names), and then eventually the call symput did its job and &a got a 4 in it at the end of the loop, and forever more your tem_&a. resolved to tem_4.

The solution? Don't use macros for this. Instead, use arrays.

  data new;
     set set1;
     total = 0;
     array tem[&counter.] tem_1-tem_&counter.;
     a = 1;
     do i = 1 to &counter; *or do i = 1 to dim(tem);
       total = total + Tem[i];
     end;
 run;

Or, of course, just directly sum them.

data new;
  set set1;
  total = sum(of tem_1-tem_4);
run;

If you REALLY like macro variables, you could of course do this in a macro do loop, though this is not recommended for this purpose as it's really better to stick with data step techniques. But this should work, anyway, if you run this inside a macro (this won't be valid in open code).

  data new;
     set set1;
     total = 0;
     %do i = 1 %to &counter;
       total = total + Tem_&i.;         
     %end;
  run;

Upvotes: 2

Related Questions