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.

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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