Solved
New Contributor
Posts: 4

# How can I use a macro numeric variable as an index in a do loop?

[ Edited ]

I'm working with arrays and I know that you can use a do loop to loop through the array and change/modify values, like the example below:

``````do i=1 to dim(SD);
if DOB43=>SD(i) and DOB56<=ED(i) then Flag=1;
end;``````

Where SD and ED are arrays created previously in the datastep.

What I want to do during the loop is actually create numbered variables.  For example:

``````%do i=2 %to dim(SD);
datediff&i.=SD(&i.)-ED(&i.-1)
%end;``````

I know the syntax is not correct for this, but the basic idea is shown. I want to be able to use the macro variable "i" as an index for the loop.  So for the first loop when i=2, I want to create the variable datediff2=SD(2)-ED(1).  Subsequent loops would create datediff3=SD(3)-ED(2), all the way up to datediff(dim(SD))=SD(dim(SD))-ED(dim(SD)-1)), whatever integer dim(SD) may be.

Is this possible or is there another method to accomplish the same thing?

Thanks

Accepted Solutions
Solution
‎07-28-2016 06:51 PM
Super User
Posts: 13,583

## Re: How can I use a macro numeric variable as an index in a do loop?

Not to mention that use of %if or %do constructs requires being placed into a %macro/%mend definition AND that your attempt would generate likely garbage code.

An array statement will create new variables. This line would create 25 variables with suffixes of 1 to 25

Array DD datediff1-datediff25;

All Replies
Super User
Posts: 3,927

## Re: How can I use a macro numeric variable as an index in a do loop?

Why not create a DATEDIFF array and continue using the ARRAY approach? Its a lot easier than introducing macros.

Solution
‎07-28-2016 06:51 PM
Super User
Posts: 13,583

## Re: How can I use a macro numeric variable as an index in a do loop?

Not to mention that use of %if or %do constructs requires being placed into a %macro/%mend definition AND that your attempt would generate likely garbage code.

An array statement will create new variables. This line would create 25 variables with suffixes of 1 to 25

Array DD datediff1-datediff25;

SAS Super FREQ
Posts: 9,373

## Re: How can I use a macro numeric variable as an index in a do loop?

Here's a quick introduction to how SAS array processing works. No macro variables needed:
https://support.sas.com/rnd/papers/sgf07/arrays1780.pdf
cynthia
New Contributor
Posts: 4

## Re: How can I use a macro numeric variable as an index in a do loop?

Thanks for your responses. With these, I think I've got it
☑ This topic is solved.