Solved
Contributor
Posts: 35

# Compute quantity in a recursive way

[ Edited ]

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.

Accepted Solutions
Solution
‎12-20-2015 06:55 PM
Super Contributor
Posts: 490

## Re: Compute quantity in a recursive way

[ Edited ]

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; ``````

All Replies
Super Contributor
Posts: 490

## Re: Compute quantity in a recursive way

``````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

Contributor
Posts: 35

## Re: Compute quantity in a recursive way

Posted in reply to mohamed_zaki
Dear @mohamed_zaki, I'm really sorry. I did a mistake including V3 in my previous toy example. I have just updated it.
Solution
‎12-20-2015 06:55 PM
Super Contributor
Posts: 490

## Re: Compute quantity in a recursive way

[ Edited ]

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; ``````

Trusted Advisor
Posts: 1,147

## Re: Compute quantity in a recursive way

[ Edited ]

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
🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

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