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:
| id | visit |
| 2 | 7/5/2014 |
| 2 | 8/30/2014 |
| 2 | 9/24/2014 |
| 4 | |
| 8 | 4/25/2014 |
| 8 | 4/26/2014 |
| 8 | 5/28/2014 |
Want:
| id | visit | last_visit_date |
| 2 | 7/5/2014 | |
| 2 | 8/30/2014 | 7/5/2014 |
| 2 | 9/24/2014 | 8/30/2014 |
| 4 | ||
| 8 | 4/25/2014 | |
| 8 | 4/26/2014 | 4/25/2014 |
| 8 | 5/28/2014 | 4/26/2014 |
Actual Result:
| id | visit | last_visit_date |
| 2 | 7/5/2014 | |
| 2 | 8/30/2014 | 7/5/2014 |
| 2 | 9/24/2014 | 8/30/2014 |
| 4 | ||
| 8 | 4/25/2014 | |
| 8 | 4/26/2014 | 9/24/2014 |
| 8 | 5/28/2014 | 4/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
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 ![]()
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 ![]()
Thanks -- exactly what I was looking for!
April 27 – 30 | Gaylord Texan | Grapevine, Texas
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!
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.