Help using Base SAS procedures

Unable to use two lag functions at once

Accepted Solution Solved
Reply
Contributor
Posts: 26
Accepted Solution

Unable to use two lag functions at once

I don't necessarily need a coding solution, but am looking to understand why this code doesn't work.

data want; set have; 

  if id=lag(id) then last_visit=lag(visit);

run;

Have:

idvisit
27/5/2014
28/30/2014
29/24/2014
4
84/25/2014
84/26/2014
85/28/2014



Want:

idvisitlast_visit_date
27/5/2014
28/30/20147/5/2014
29/24/20148/30/2014
4
84/25/2014
84/26/20144/25/2014
85/28/20144/26/2014

Actual Result:

idvisitlast_visit_date
27/5/2014
28/30/20147/5/2014
29/24/20148/30/2014
4
84/25/2014
84/26/20149/24/2014
85/28/20144/26/2014

I believe I could also accomplish this with a retain statement, but it eventually worked after outright creating the variable lag_visit (below).   I don't completely understand why it was necessary to do this.

data want; set have; 

     lag_visit=lag1(visit_dt);

     if id=lag(id) then last_visit=lag_visit;

run;

Thanks,

K


Accepted Solutions
Solution
‎08-03-2015 06:22 PM
Super User
Posts: 19,869

Re: Unable to use two lag functions at once

Lag function creates a queue. If you execute it conditionally, then it isn't updated every iteration.

In general, don't use Lag functions in conditional statements.

This paper illustrates your issue and explains it better than I can Smiley Happy

http://www.howles.com/saspapers/CC33.pdf

View solution in original post


All Replies
Solution
‎08-03-2015 06:22 PM
Super User
Posts: 19,869

Re: Unable to use two lag functions at once

Lag function creates a queue. If you execute it conditionally, then it isn't updated every iteration.

In general, don't use Lag functions in conditional statements.

This paper illustrates your issue and explains it better than I can Smiley Happy

http://www.howles.com/saspapers/CC33.pdf

Contributor
Posts: 26

Re: Unable to use two lag functions at once

Thanks -- exactly what I was looking for!

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 280 views
  • 0 likes
  • 2 in conversation