Hey all,
I'm relatively new to SAS and having trouble figuring this out. If anyone could help me out, I'd appreciate it.
Here is what i have,
Date Port_no Liquidity
011985 1 2.3
021985 1 1.4
031985 1 2.4
041985 1 3.4
. . .
. . .
.
122011 1 2.4
011985 2 4.5
021985 2 5.4
...
122011 2 4.5
The port_no goes up to 25.
What I'm interested in is creating a Lag variable for Liquidity given each port_no. A simple newVar=lag( liquidity) would create a lag of port_no 2 from 1/1985 with that of port_no 1 of 12/2011. Therefore, i was wondering how to create lag variables for all port_no given that the original variable also falls in that port_no.
Thank you for your help in advance. I'd appreciate any kind of help. Thanks again.
Hi,
Assuming your data is sorted by port_no:
data want;
set have;
by port_no;
newVar=lag( liquidity);
if first.port_no then newVar=.;
run;
/*If not sorted, then need to sort it first*/
proc sort data=have;
by port_no date;
run;
Hi,
Assuming your data is sorted by port_no:
data want;
set have;
by port_no;
newVar=lag( liquidity);
if first.port_no then newVar=.;
run;
/*If not sorted, then need to sort it first*/
proc sort data=have;
by port_no date;
run;
Hey Linlin, appreciate your help. I tried to use the same thing to create a second lag/two lag , i.e. lag2(liquidity), but seems like it doesn't work for that. Could you please tell me how to go about that.
thank you. I really do appreciate the help. Thanks.
I figured it out, thank you.
try the code below:
data have;
input Date $ Port_no Liquidity;
cards;
011985 1 2.3
021985 1 1.4
031985 1 2.4
041985 1 3.4
122011 1 2.4
011985 2 4.5
021985 2 5.4
122011 2 4.5
;
data want(drop=count);
set have;
by port_no;
new1=lag(Liquidity);
new2=lag2(Liquidity);
if first.port_no then do;
new1=.;
new2=.;
count=0;
end;
count+1;
if count=2 then new2=.;
run;
proc print;run;
Obs Date Port_no Liquidity new1 new2
1 011985 1 2.3 . .
2 021985 1 1.4 2.3 .
3 031985 1 2.4 1.4 2.3
4 041985 1 3.4 2.4 1.4
5 122011 1 2.4 3.4 2.4
6 011985 2 4.5 . .
7 021985 2 5.4 4.5 .
8 122011 2 4.5 5.4 4.5
Linlin
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!
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.