03-07-2017 03:05 PM
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!
03-07-2017 03:42 PM
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.
03-07-2017 04:05 PM
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;
03-07-2017 04:16 PM
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;
03-07-2017 04:48 PM
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);
Then within the DATA step that creates all 80 additional variables:
%all_lags (varlist=VarA VarB VarC ....... VarT)
03-07-2017 05:38 PM
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.