BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
abdulla
Pyrite | Level 9
gvkeyfyearatwant
1001200112.3.
1001200213.612.3
1001200312.613.6
1001200411.912.6
1002200113.4.
1002200217.713.4
1002200318.417.7
1002200415.118.4

 

data want;

set have;

by gvkey fyear;

if first.gvkey then want=.;

else want=lag(at);

run;

 

My data is already sorted. I am not getting the expected result. What is the mistake here? 

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Never use LAG conditionally (unless you really know what you are doing). Slightly change your code:

data want;
set have;
by gvkey fyear;
want = lag(at);
if first.gvkey then want = .;
run;

This is necessary because LAG will only put a value into the queue when it is called.

View solution in original post

5 REPLIES 5
mklangley
Lapis Lazuli | Level 10

@abdulla   Can you include both your input data and your expected result?

abdulla
Pyrite | Level 9
The first three columns are my data and the fourth column is my expected result.
Reeza
Super User
Lag cannot be calculated conditionally, so calculate it all the time and then set it to missing AFTER.

want = lag(at);
if first.gvkey then call missing(want);
Kurt_Bremser
Super User

Never use LAG conditionally (unless you really know what you are doing). Slightly change your code:

data want;
set have;
by gvkey fyear;
want = lag(at);
if first.gvkey then want = .;
run;

This is necessary because LAG will only put a value into the queue when it is called.

abdulla
Pyrite | Level 9
Thank you

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
  • 5 replies
  • 1681 views
  • 2 likes
  • 4 in conversation