Solved
Contributor
Posts: 36

# Moving average projection through data step

Hi,

I am trying to do a moving average forecast with data step and lag LAG function. But I am not getting the desired result.

``````data input;
input slope_med 4.2 segment \$2. product_type \$2. trans_yearmon 8. ;
datalines;
0.1 A ZZ 201601
0.2 A ZZ 201602
0.3 A ZZ 201603
0.4 A ZZ 201604
0   A ZZ 201605
0   A ZZ 201606
0   A ZZ 201607
;

data output1;
format lag_slope lag2_slope lag3_slope slope_med 6.2;
set input;
lag_prod = lag(product_type);
lag_seg = lag(segment);
if lag_prod = product_type and lag_seg = segment  then do;
lag_slope = lag(slope_med);
lag2_slope = lag2(slope_med);
lag3_slope = lag3(slope_med);
if trans_yearmon ge 201605 then slope_med = mean(lag_slope, lag2_slope, lag3_slope);
end;
if trans_yearmon ge 201605 then output;
run;
``````

I want to predict slope_med for 201605, 201606, 201607.

When I am projecting the value for 201606 I should use the slope med value for - 201603,201604 and the forecasted value of 201605.
Can you kindly let us know what modifications should I make in the above datastep to get the desired result ?

``````data desired;
input slope_med 4.2 segment \$2. product_type \$2. trans_yearmon 8.;
datalines;
0.3 A ZZ 201605
0.33 AZZ 201606
0.34 AZZ 201607
;
``````

Accepted Solutions
Solution
‎06-21-2016 03:12 PM
Super User
Posts: 10,778

## Re: Moving average projection through data step

``````data input;
input slope_med 4.2 segment \$2. product_type \$2. trans_yearmon 8. ;
datalines;
0.1 A ZZ 201601
0.2 A ZZ 201602
0.3 A ZZ 201603
0.4 A ZZ 201604
0   A ZZ 201605
0   A ZZ 201606
0   A ZZ 201607
;
run;

data want;
set input;
array x{3} _temporary_;
if slope_med ne 0 then temp=slope_med;
else do;temp=mean(of x{*});slope_med=temp;end;
do i=2 to dim(x);
x{i-1}=x{i};
end;
x{3}=temp;
drop i temp;
run; ``````

All Replies
Solution
‎06-21-2016 03:12 PM
Super User
Posts: 10,778

## Re: Moving average projection through data step

``````data input;
input slope_med 4.2 segment \$2. product_type \$2. trans_yearmon 8. ;
datalines;
0.1 A ZZ 201601
0.2 A ZZ 201602
0.3 A ZZ 201603
0.4 A ZZ 201604
0   A ZZ 201605
0   A ZZ 201606
0   A ZZ 201607
;
run;

data want;
set input;
array x{3} _temporary_;
if slope_med ne 0 then temp=slope_med;
else do;temp=mean(of x{*});slope_med=temp;end;
do i=2 to dim(x);
x{i-1}=x{i};
end;
x{3}=temp;
drop i temp;
run; ``````
🔒 This topic is solved and locked.