Solved
Contributor
Posts: 50

# Rolling forward calculations

Dear community,

I would be glad, if you could help me with the following problem.

What I am aiming at implementing is the following:

In the first row, I calculate a specific variable, e.g., y = x*a;

Said y shall be carried forward to the second row a play the role as the new x. The same calculation is performed, i.e., y=x*a, whereby the x for the second row is the y from the first row;

That is the input

and output

I am considering.

It would be kind, if you could give me a hint, on how to I tackle this kind of problem?

As SAS "work" row to row (as I have understood), it should give a "trick"?

Otherwise, for each step, I would have to create an index, separate the y, merge the y to the next observation, replace x with the carried-forward-y and calculate once again.

This would result in a huge amount of data steps.

``````data have;
input x a;
datalines;
1	2
.	2
.	2
.	2
.	2
.	2
.	2
.	2
.	2
.	2
;
run;``````

Accepted Solutions
Solution
‎08-14-2016 08:57 AM
Respected Advisor
Posts: 3,167

## Re: Rolling forward calculations

Posted in reply to Sinistrum

A good example of 'RETAIN';

``````data want;
set have;
retain y;
if _n_ ne 1 then x=y;
y=x*a;
run;``````

All Replies
Super Contributor
Posts: 324

## Re: Rolling forward calculations

Posted in reply to Sinistrum

Here is a way by data step. Replace x by everytime before the next iteration like:

``````data have;
a = 2;
do i = 1 to 10;
if i = 1 then x = 1;
y = x * a;

output;
x = y;
end;
drop i;
run;
proc print; run;``````

Hope this is an acceptable solution to you.

Solution
‎08-14-2016 08:57 AM
Respected Advisor
Posts: 3,167

## Re: Rolling forward calculations

Posted in reply to Sinistrum

A good example of 'RETAIN';

``````data want;
set have;
retain y;
if _n_ ne 1 then x=y;
y=x*a;
run;``````
Contributor
Posts: 50

## Re: Rolling forward calculations

Hello,

this is enormous.

I really had allready implemented it via a %macro %Do Loop.

The amount of time if do save is astonishing.

Thank you so much for this - I need this very procedure "over an over" so this really changes the game.

As I do have to implement it for more than one variable, would you mind considering if I have transferred it correctly to a setting more closely to the actual one?

``````data want;
set have;

retain x_end y_end z_end;

if _n_ ne 1 then x=x_end;
if _n_ ne 1 then y=y_end;
if _n_ ne 1 then z=z_end;

x_end		=		intercept1

+		a*x
+		b*y
+		c*z
;

y_end		=		intercept2

+		d*x
+		e*y
+		f*z

;

z_end		=		intercept3

+		g*x
+		h*y
+		i*z
;

run;``````

So, former y is now "x_end";

Especially, the three ifs are a concern of mine - could I achieve a better solution?

But, nonetheless, your very answer means a huge leap indeed for me.

Once again, thank you so much.

☑ This topic is solved.

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

Discussion stats
• 3 replies
• 396 views
• 3 likes
• 3 in conversation