kyro1021
kyro1021

Reputation: 31

SAS: array passed to macro

I am trying to use a macro to label some array variables in SAS to avoid having to type a lot of lines of code. What I'm trying to do is basically this:

%macro LABEL_ARRAY(V);
 %DO I = 1 %TO 4;
   %let variablename=&V(&I);
   array1[&I] = "Value of &variablename"
 %END
%MEND LABEL_ARRAY;

So, V is an array containing the corresponding variable names for the positions in the array array1. I'm trying to do this for more than 4 variables per array and for numerous arrays, but that's the basic idea. Basically what is happening is the array1[&I] which I would want to eventually say array1[1] for the first entry, is not using the value of I but rather just saying &I, same thing with &variablename.

Any suggestions on what might be happening? Thanks.

Upvotes: 2

Views: 558

Answers (1)

Joe
Joe

Reputation: 63424

There is no built-in array type in the macro language (there is in fact no types at all in the macro language) in SAS.

Macro arrays are instead handled through multiple resolution of the ampersand. I encourage you to read this answer for more information on exactly how this works in the general case.

However, for the specific case of macro variable "arrays", it is worth explaining exactly how they work.

What you have is likely a set of macro variables like so:

%let v = Color;
%let color1=Blue;
%let color2=Red;
%let color3=Green;

And you want to be able to do:

%do _i = 1 to 3;
  %let thisColor = &color&_i;
%end;

Except that doesn't work - because &color resolves (and likely resolves to &color if you didn't separately define taht), and &i resolves to 1, leaving you with &color1 but not Blue, plus a warning message about &color not resolving.

What you need to do is delay the resolution of &color until &_i resolves. You can do that by adding a second ampersand.

%do _i = 1 to 3;
  %let thisColor = &&color&_i;
%end;

What that does is tells SAS to resolve the two && to one & but keep it in the queue for resolving; then on a second pass, resolve that single &. So you have

&&color&_i
&color1
Blue

Instead of stopping at the second level.

This is explained in more detail in my paper Unravelling the Knot of Ampersands, and Ron Fehd's Array: Construction and Usage of Arrays of Macro Variables.

Upvotes: 2

Related Questions