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;
⏰
Today is the last day to save with the early bird rate! Register today for just $695 - $100 off the standard rate.
Plus, pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.