Search code examples
loopssassas-macro

Dynamic macro variable access SAS


I've used call symputx to create a list of macro variables Item 1 to Item N and now I want to transfer them to an array in another datastep so that spot 1 in the array gets Item1, spot 2 gets Item2, etc.

    do j=1 to &num_OR;
    rulesUsed{j}=&&Item&j;
    end;

I read that the double ampersand syntax is the way to reference macro variables like this but I keep getting all sorts of errors. I'm sure there's a simple way around this but I'm new to SAS and no document I've read through that's come up in searches mentions this exact type of problem.


Solution

  • The short answer is: don't do this, in general. Macro variables aren't a great way to store data, and there's nearly always a better way.

    But if you need to, your issue here is that the macro variable can't use the data step variable.

     do j=1 to &num_OR;
        rulesUsed{j}=&&Item&j;
     end;
    

    j is a data step variable, not a macro variable, and so it's not &j. You need to either:

    1 - Use symget to retrieve the macro variable. That's a data step function that takes a normal data step character argument (so a variable, a " " string, etc.) and returns the macro variable with that name. So

    rulesUsed[j] = symget(cats("item",j));
    

    2 - Use a macro loop to retrieve the macro variable.

    %do j = 1 %to &num_or;
      rulesUsed[&j.] = &&item&j;
    %end;
    

    Either of these methods work fine.