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

sas-innovate-2024.png

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.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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