BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
mark_ph
Calcite | Level 5

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.

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
mohamed_zaki
Barite | Level 11

 

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; 

 

View solution in original post

4 REPLIES 4
mohamed_zaki
Barite | Level 11
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

mark_ph
Calcite | Level 5
Dear @mohamed_zaki, I'm really sorry. I did a mistake including V3 in my previous toy example. I have just updated it.
mohamed_zaki
Barite | Level 11

 

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; 

 

Jagadishkatam
Amethyst | Level 16

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;

 

Thanks,
Jag

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1283 views
  • 0 likes
  • 3 in conversation