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.
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}.
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.
Your problem is difficult to understand, please post example have and want datasets.
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.
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}.
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
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.