BookmarkSubscribeRSS Feed
pawandh
Fluorite | Level 6

I have this code

data t;

input cust_id date:date9.  sales;

001 23feb2017 100

001 22jan2016 200

001 23mar2017 300

002 01june2015 200

002 03aug2016 300

002 05april2016 400

;run;

data t1;

set t;

by cust_id;

if first.cust_id=0 then x =lag(date);

run;

I'm getting a missing vcalue in second observation, where I should get the date of first observation?

Except this it's working fine.

2 REPLIES 2
BrunoMueller
SAS Super FREQ

Hi

 

the LAG function has to be executed for every row.

 

Find below the changed code. The LAG function is executed for every row, if we are on the first row of a group we reset the value for the variable x.

 

data t;
  input cust_id date:date9.  sales;

  format date date9.;
  cards;
001 23feb2017 100
001 22jan2016 200
001 23mar2017 300
002 01jun2015 200
002 03aug2016 300
002 05apr2016 400
;

data t1;
  set t;
  by cust_id;
  x =lag(date);

  if first.cust_id=1 then do;
    x = .;
  end;
  format x date9.;
run;

Bruno

Kurt_Bremser
Super User

To expand on @BrunoMueller's answer: The lag() function is a First-In-First-Out queue, which is only fed when the function is called. If you call it conditionally, everytime the condition is not met, the current value in the variable will not be fed into the queue. Since you did not call lag() in the first data step iteration, its content was still missing when you called it in the second iteration. You'll also get a wrong value after each first. condition, as you'll still have the value from the previous last. observation.

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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