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!
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.
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.