Hi All,
I need to create 4 lag terms each for 15 different variables, is there a way to create macro for 4 lag terms for each of my variable in SAS UE.
Usually, I use Var A1=lag1(VarA);
for creating lag but what if we have more than 20 variables and need to create more than 4 lag terms?
Thanks in advance for any suggestions/advise/cool insights!
RJ
Since your macro would have to create 20*4 (per the example) NEW variables how are you going to use them? How will you know what the names are for other uses? You may need to provide a bit more detail about what the overall goal and further processes for this to get something workable.
I'd use proc expand with a macro loop.
But I'd also suggest looking at PROC TIMESERIES to see if it's helpful in this situation.
@rj I modified the macro above to work for multiple lags & multiple variables.
I don't understand what do you mean by "4 lag terms".
If you need create lag to many variables you can use next macro, as in this demo:
%macro lag(vars);
%let m = %sysfunc(countw(&vars));
%do i=1 %to &m;
%let var = %scan(&vars,&i);
%do; lag_&var = lag(&var); %end;
%end;
%mend lag;
data test;
set sashelp.class;
%lag(age height name sex); /* variables to create lag_xxx to var xxx */
run;
And add another loop/parameter to do more lags.
Mostly stolen from @Shmuel
%macro lag(vars, lags);
%let m = %sysfunc(countw(&vars));
%do i=1 %to &m;
%let var = %scan(&vars,&i);
%do j=1 %to &lags;
%do;
lag_&var.&j = lag&j(&var);
%end;
%end;
%end;
%mend lag;
data test;
set sashelp.class;
%lag(age height name sex, 4); /* variables to create lag_xxx to var xxx */
run;
You can't get around needing all these statements. But what you can do is have macro language generate them for you. For example:
%macro all_lags (varlist=);
%local i j nextvar;
%do i=1 %to %sysfunc(countw(&varlist));
%let nextvar = %scan(&varlist, &i);
%do j=1 %to 4;
&nextvar&j = lag&j(&nextvar);
%end;
%end;
%mend all_lags;
Then within the DATA step that creates all 80 additional variables:
%all_lags (varlist=VarA VarB VarC ....... VarT)
Note that all of these approaches may have issues with 1) long variable names: adding 4 or more characters to create the new variables means that an existing variable with more than 28 characters could create an invalid variable name and 2) could result in collision of names, using one that already exists in the data set.
It is a lot easy for IML code. proc iml; use sashelp.class; read all var{age}; close; lag=lag(age,1:4); print lag; quit;
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
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.
Ready to level-up your skills? Choose your own adventure.