BookmarkSubscribeRSS Feed
Xinhui
Obsidian | Level 7

Hi there

I have a variable "Price" and I would like to creat a new variable "P1” which is lag 5 of "price" by variable "ticker" . I used the following code

data full;
set master;
By ticker;
P1=lag5(PRICE);
IF NOT FIRST.Ticker THEN P1= .;
run;

However, the code not doing well. 

Plase let me know how to improve. 

 

Thanks in advance. 

 

2 REPLIES 2
PeterClemmensen
Tourmaline | Level 20

I'm guessing that the problem is that your code does not handle by groups well?

 

If so. There are several ways to handle this. In the data step, you could do something like this

 

data have(drop=i);
   do ticker='a', 'b', 'c';
      do i=1 to 10;
         price=rand('integer', 1, 100);
         output;
      end;
   end;
run;

data want(drop=t5);
   set have;
   p5=lag5(price);
   t5=lag5(ticker);
   if t5 ne ticker then call missing(p5);
run;

Result:

 

ticker price p5 
a      1     . 
a      76    . 
a      6     . 
a      99    . 
a      77    . 
a      59    1 
a      73    76 
a      10    6 
a      91    99 
a      1     77 
b      89    . 
b      4     . 
b      21    . 
b      88    . 
b      26    . 
b      38    89 
b      58    4 
b      95    21 
b      72    88 
b      15    26 
c      46    . 
c      59    . 
c      78    . 
c      84    . 
c      26    . 
c      98    46 
c      16    59 
c      61    78 
c      54    84 
c      38    26 
Reeza
Super User

Do you have SAS/ETS? If so, try PROC EXPAND. 

 

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 751 views
  • 0 likes
  • 3 in conversation