S420L
S420L

Reputation: 117

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.

Upvotes: 0

Views: 502

Answers (2)

Tom
Tom

Reputation: 51566

If you have a dataset like below:

data have ;
  ruleno+1;
  input rule $20. ;
cards;
Value1
Value2
Value3
;

You can convert it to wide using PROC TRANSPOSE.

proc transpose data=have out=want(drop=_name_) prefix=rulesUsed ;
  var rule;
  id ruleno;
run;

enter image description here

Upvotes: 0

Joe
Joe

Reputation: 63424

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.

Upvotes: 1

Related Questions