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

Hi everyone,

 

I need to calculate lag value that is not constant from time to time.

 

For example for first entry I want lag6() for second entry I want lag9() for third entry lag999(). 

 

Is there any way to do it? I tried to use %let function, but macro can be only constant so it was not working. 

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Array code:

data want;
set have;
array mylags{1000} _temporary_;

/* your processing here */

/* at the end of the step */
do mylagindex = dim(mylags) to 2 by -1;
  mylags{mylagindex} = mylags{mylagindex-1};
end;
mylags{1} = x;
drop mylagindex;
run;

In your code, mylags{1} is equivalent to lag(x), and mylags{999} to lag999(x). The only thing you need to adapt in that code is the size of the array and which variable's value you assign to mylags{1}.

View solution in original post

4 REPLIES 4
Tom
Super User Tom
Super User

Since in general you will need to execute LAGn() function call on every observation just do that and store the results somewhere that you can conditionally retrieve them.

data want;
  set have ;
  x_lag6 = lag6(x);
  x_lag9 = lag9(x);
  x_lag999 = lag999(x);
  if entry=1 then new_var = x_lag6 ;
  else if entry=2 then new_var=x_lag9;
  else new_var=x_lag999;
run;

Provide a more complete description of what you are actually trying to do to see if there might be a better way to do what you want. Most likely one that does not use any of the LAGn() functions.

andreas_lds
Jade | Level 19

Your problem is difficult to understand, please post example have and want datasets.

Kurt_Bremser
Super User

How many lags would you need at most?

Instead of the many function calls, I'd use either an array or a hash to create a sufficiently long FIFO chain.

Kurt_Bremser
Super User

Array code:

data want;
set have;
array mylags{1000} _temporary_;

/* your processing here */

/* at the end of the step */
do mylagindex = dim(mylags) to 2 by -1;
  mylags{mylagindex} = mylags{mylagindex-1};
end;
mylags{1} = x;
drop mylagindex;
run;

In your code, mylags{1} is equivalent to lag(x), and mylags{999} to lag999(x). The only thing you need to adapt in that code is the size of the array and which variable's value you assign to mylags{1}.

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 647 views
  • 0 likes
  • 4 in conversation