## The index i in do loop

Solved
Occasional Contributor
Posts: 12

# The index i in do loop

Hi folks,

I have some problem to write the following code by using a do loop. Say I have a column and its name is var1. Now I want to generate the second column and its name is var2, where var2=lag(var1). Similarly, var3=lag(var2) etc.

data want;

set column1;

var2=lag(var1);

var3=lag(var2);

var4=lag(var3);

run;

When I try to use a do loop:

data want;
set column1;
do i=2 to 4;
vari=lag(var(i-1));
run;

Obviously it's not working cuz the i is mixed with the string. Any idea on how to fix it? Thanks.

Accepted Solutions
Solution
a month ago
Super User
Posts: 10,267

## Re: The index i in do loop

[ Edited ]

Use an array

``````data want;
set column1;
array vars{4} var1-var4;
do i=2 to 4;
vars{i}=lag(vars{i-1});
end;
run;``````

Edit: closed the do block.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code

All Replies
Super User
Posts: 6,781

## Re: The index i in do loop

Here's one of the missing pieces.  You will need to set up an array:

array vars {4} var1-var4;

Then you can refer to elements in the array as vars{i}:

vars{i}=lag(vars(i-1));

What is the "MUST" part of the question?  MUST use a DO loop?  MUST get the right result?  MUST use LAG?

You might be able to solve this without fancy tools, just knowledge of how the DATA step works:

data want;

var4=var3;

var3=var2;

var2=var1;

set have;

retain var1-var4;

run;

Occasional Contributor
Posts: 12

## Re: The index i in do loop

I am fairly new to SAS so I just want to seek all the possibilities. I see array is a very good idea to solve this problem, but I just can't help thinking about do loop. Still, I appreciate your help.
Solution
a month ago
Super User
Posts: 10,267

## Re: The index i in do loop

[ Edited ]

Use an array

``````data want;
set column1;
array vars{4} var1-var4;
do i=2 to 4;
vars{i}=lag(vars{i-1});
end;
run;``````

Edit: closed the do block.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
☑ This topic is solved.