BookmarkSubscribeRSS Feed
bssturgi
Calcite | Level 5

I have panel data, and I am trying to create lags. The code below seems to be generating the desired results for the first lag of the variable of interest.

 

proc sort data=Pooled_Panel;
by Country Year;
run;

data Pooled_Panel_lags;
set Pooled_Panel;
by Country Year;
Lag_EFWS=Lag(EFWS);
If First.Country then do;
   Lag_EFWS=.;
end;
run;

My question is this.  How do I do this for the second lag?  I know to use Lag2(variable), but what type of if-then statement do I need here?  I don't want the second lag to be the value two rows before if that value corresponds to another country.  I'm using SAS 9.4.

3 REPLIES 3
Reeza
Super User

Do you have SAS/ETS? If so, you can do this a bit more easily with the convert statement. 

 

If you don't, you're stuck with a counter. Create a counter variable using RETAIN and then delete any less than what you need.

 

 

 

data Pooled_Panel_lags;
set Pooled_Panel;
by Country Year;

Lag_EFWS  = Lag(EFWS);
Lag_EFWS2 = Lag2(EFWS);
 
If First.Country then counter=0;

counter+1;

if counter <= 1 then call missing(lag_efws, lag_efws2);
if counter <= 2 then call missing(lag_efws2);



run;

 

I can't test it, but this may work as well, make sure to only Keep what you need in each data set.

 

 

data want;
merge pooled_panel
           pooled_panel (firstobs=2 rename = (efws = lag_efws) keep=(PUT VARIABLE LIST HERE))
           pooled_panel (firstobs=3) rename = (efws = lag_efws2) keep=(PUT VARIABLE LIST HERE));

by country;

run;

 

bssturgi
Calcite | Level 5

Thank you!  The code you provided with the counter has done the trick.

 

I don't have SAS/ETS, but I think one of my colleagues may have at, and I may get it in the future.  Could you tell me how I would do this with the convert statement?

SAS Innovate 2025: Register Now

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!

Multiple Linear Regression in SAS

Learn how to run multiple linear regression models with and without interactions, presented by SAS user Alex Chaplin.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 3 replies
  • 1350 views
  • 1 like
  • 2 in conversation