Dear All,
I have the following dataset:
data have; input id V1 V2; datalines; 1 10 3 1 . 4 1 . 5 2 20 5 2 . 7 2 . 8;
I would like to obtain the following dataset want. That is, I want
V1 = lag(V1)+V2 for those observations such that first.id is not true (starting from the second one of each id group)
data want;
input id V1 V2;
datalines;
1 10 3
1 14 4
1 19 5
2 20 5
2 27 7
2 35 8;
Any help would e highly appreciated.
If this is what you want then you do not need Lag()
data want (drop=v12sum);
set have;
by id;
retain v12sum;
if first.id then v12sum=v1;
else do ;
v12sum=v12sum+v2;
v1=v12sum;
end;
data want (drop=lag_v1) ;
set have;
by id;
lag_v1=lag(V1);
if first.id then V3=V1;
else V3=lag_v1+4;
run;
I think you have mistaken the value of V3 in the last row in your data want
If this is what you want then you do not need Lag()
data want (drop=v12sum);
set have;
by id;
retain v12sum;
if first.id then v12sum=v1;
else do ;
v12sum=v12sum+v2;
v1=v12sum;
end;
Though the solution is already provided, here is an alternative approach.
Hope you like it.
data want;
set have(rename=v1=_v1);
retain v1;
by id;
if first.id then v1=_v1;
else v1=sum(v1,v2);
run;
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 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.