BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Obsidian | Level 7

## Loop with a lag function

I need to calculate rows with a lag variable but struggling to do that. Essentially it should follow this function

For first row, D = A+B

For subsequent rows, D = lag(D)+A

Any guidance?

 Date A B C D 202303 254509298.4 5644500000 5899009298 202304 125121716.6 5899009298 6024131015 202305 224951659.8 6024131015 6249082675 202306 189510381.8 6249082675 6438593057 202307 225507645.3 6438593057 6664100702 202308 332878952.2 6664100702 6996979654 202309 69832226.1 6996979654 7066811880 202310 155360032.1 7066811880 7222171912 202311 212155525.5 7222171912 7434327438 202312 104031780 7434327438 7538359218 202401 67473757.38 7538359218 7605832975 202402 120658625.5 7605832975 7726491601
1 ACCEPTED SOLUTION

Accepted Solutions
Super User

## Re: Loop with a lag function

No LAG() needed.  Just make sure D is a NEW variable and RETAIN its value.

``````data want ;
set have;
retain d;
if _n_=1 then d=a+b;
else d=d+a ;
run;``````
2 REPLIES 2
Super User

## Re: Loop with a lag function

No LAG() needed.  Just make sure D is a NEW variable and RETAIN its value.

``````data want ;
set have;
retain d;
if _n_=1 then d=a+b;
else d=d+a ;
run;``````
Obsidian | Level 7

## Re: Loop with a lag function

Oh brilliant! So simple. Thanks so much!
Discussion stats
• 2 replies
• 232 views
• 1 like
• 2 in conversation