Hi Everybody,
I have a real trouble with a mean calculation.In fact, I want to calculate the rolling mean for this set using a array statement.
Here are samples of what I have and what I want. In others words :
m0=mean(v0)=v0 ; m1=mean(v0, v1) ; m2=mean(of v0 -v2) & m3=mean(of v0 -v3).
I tried this code but got an error :
data have;
input v0 v1 v2 v3;
datalines;
2 3 5 4
4 6 2 8
3 4 7 2
;
run;
data want;
input m0 m1 m2 m3;
datalines;
2 2 3 3.25
4 5 4 5
3 3.5 5 4.25
;
run;
data want;
set have;
array temp(0:3) T0 - T3;
array wish(0:3) m0 - m3;
do i = 0 to 3;
if i = 0 then do;
temp(i) = v0;
wish(i) = temp(i)/(i+1);
end;
else temp(i) = temp(i-1) + vi;
wish(i) = temp(i)/(i+1);
end;
run ;
NOTE: Variable vi is uninitialized.
NOTE: Missing values were generated as a result of performing an operation on missing values.
Each place is given by: (Number of times) at (Line):(Column).
9 at 1062:30 9 at 1063:22
NOTE: There were 3 observations read from the data set WORK.HAVE.
NOTE: The data set WORK.WANT has 3 observations and 14 variables.
Will appreciate any kind of help!
I agree with @RW9 that if you do not have more variables than in your sample data, his is the simplest way to go..
However, if you do have more variables than that, then do something like this
data have;
input v0 v1 v2 v3;
datalines;
2 3 5 4
4 6 2 8
3 4 7 2
;
run;
data want(keep=m0-m3);
set have;
array temp{*} v0-v3;
array wish{*} m0-m3;
sum=0;
do i=1 to dim(temp);
sum+sum(of temp[i]);
wish[i]=sum/i;
end;
run;
This:
else temp(i) = temp(i-1) + vi;
vi is never defined anywhere, I assume you want another array in there. Anyways, something like:
data want; set have; array m{3}; m{1}=mean(v0); m{2}=mean(v0,v1); m{3}=mean(v0,v1,v2); run;
Is the simplest method for just 3 variables, adding arrays and loops just expands the code.
I agree with @RW9 that if you do not have more variables than in your sample data, his is the simplest way to go..
However, if you do have more variables than that, then do something like this
data have;
input v0 v1 v2 v3;
datalines;
2 3 5 4
4 6 2 8
3 4 7 2
;
run;
data want(keep=m0-m3);
set have;
array temp{*} v0-v3;
array wish{*} m0-m3;
sum=0;
do i=1 to dim(temp);
sum+sum(of temp[i]);
wish[i]=sum/i;
end;
run;
Anytime, glad to help 🙂
You do not need it. You would need it, had I written
sum=sum+sum(of temp[i]);
instead of
sum+sum(of temp[i]);
Also, there seems to be a mismatch between what you say you want and your "want" data set.
Eg you say you want m1=mean(v0, v1) , which for the first observation means that m1=mean(2,3)=2.5, but m1=2 in your "want" data set? 🙂
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.