Hi, My code calculate moving sum (i to i+3). The last 2 rows have issue where it double count the last value. Can you please help me to fix it? Thanks, HHC
data have;
input value;
datalines;
1
2
3
4
5
6
7
8
9
10
;run;
data want;
set have nobs=totalobs;
i+1;
total=0;
do j=i to i+2;
set have (keep = value ) point=j nobs=nobs;;
total= total + value;
*output;
end;
run;
data have;
input value;
datalines;
1
2
3
4
5
6
7
8
9
10
;run;
data want;
set have nobs=totalobs;
i+1;
total=0;
do j=i to min(i+2,totalobs);
set have (keep = value rename =(value=v)) point=j ;
total= total + v;
*output;
end;
run;
data have;
input value;
datalines;
1
2
3
4
5
6
7
8
9
10
;run;
data want;
merge have
have(firstobs=2 keep=value rename=(value=value1))
have(firstobs=3 keep=value rename=(value=value2)) ;
total=sum(value,value1,value2);
run;
Please show what you expect/want for output.
Do you thing the bit in your log that looks like this might have some bearing?
totalobs=10 value=10 i=9 total=29 j=12 nobs=10 _ERROR_=1 _N_=9 totalobs=10 value=10 i=10 total=30 j=13 nobs=10 _ERROR_=1 _N_=10
When POINT exceeds the number of records in the data set what do you think happens?
Maybe (guessing)
data want2; set have nobs=totalobs; i+1; total=0; do j=i to i+2; set have (keep = value ) point=j nobs=nobs; if j>nobs then stop; total= total + value; *output; end; run;
Perhaps-
do j=i to min(i+2,totalobs);
?
@novinosrin wrote:
Perhaps-
do j=i to min(i+2,totalobs);
?
I looked at that too. One of the reasons I asked for expected out come.
data have;
input value;
datalines;
1
2
3
4
5
6
7
8
9
10
;run;
data want;
merge have
have(firstobs=2 keep=value rename=(value=value1))
have(firstobs=3 keep=value rename=(value=value2)) ;
total=sum(value,value1,value2);
run;
Since you need to look ahead, @Ksharp 's answer is the way to go. if you wanted to "look back", a temporary array would be best:
%let size=3;
data want;
set have;
array window {0:%eval(&size.-1)} _temporary_;
window{mod(_n_,&size.)} = value;
total = sum(of window{*});
run;
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.
Ready to level-up your skills? Choose your own adventure.