BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
liyongkai800
Obsidian | Level 7

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.

1 ACCEPTED SOLUTION
3 REPLIES 3
Astounding
PROC Star

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;

 

liyongkai800
Obsidian | Level 7
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.

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 1905 views
  • 2 likes
  • 3 in conversation