Hello,
I was hoping someone could help me with some codes to determine the mean across positive values variables (MPOS). For example, MPOS (Year=2000)= avg (var1+var4)
MPOS (Year=2001)= avg (var2+var3)
MPOS (Year=2002)= avg (var1+var2)
......
Year | Var1 | Var2 | Var3 | Var4 | MPOS |
2000 | 23 | -10 | -5 | 22 | 22.5 |
2001 | -1 | 10 | 33 | -20 | 21.5 |
2002 | 10 | 20 | -30 | -10 | 15 |
2003 | 20 | -10 | 10 | -10 | 15 |
2004 | 8 | 10 | 3 | -12 | 7 |
2005 | 10 | -5 | -23 | -11 | 10 |
Declare var1 through var4 as an array. Copy only positive elements of that array to a new array. Use the MEAN function on that new array:
data have;
input Year Var1 Var2 Var3 Var4 MPOS;
datalines;
2000 23 -10 -5 22 22.5
2001 -1 10 33 -20 21.5
2002 10 20 -30 -10 15
2003 20 -10 10 -10 15
2004 8 10 3 -12 7
2005 10 -5 -23 -11 10
run;
data want (drop=_:);
set have;
array var {*} var1-var4;
array _tmp {4};
do _i=1 to dim(var);
_tmp{_i}=ifn(var{_i}>0,var{_i},.);
end;
meanvar=mean(of _tmp{*});
run;
Declare var1 through var4 as an array. Copy only positive elements of that array to a new array. Use the MEAN function on that new array:
data have;
input Year Var1 Var2 Var3 Var4 MPOS;
datalines;
2000 23 -10 -5 22 22.5
2001 -1 10 33 -20 21.5
2002 10 20 -30 -10 15
2003 20 -10 10 -10 15
2004 8 10 3 -12 7
2005 10 -5 -23 -11 10
run;
data want (drop=_:);
set have;
array var {*} var1-var4;
array _tmp {4};
do _i=1 to dim(var);
_tmp{_i}=ifn(var{_i}>0,var{_i},.);
end;
meanvar=mean(of _tmp{*});
run;
This worked out for me.
Thank you!!
data have;
input Year Var1 Var2 Var3 Var4 ;
datalines;
2000 23 -10 -5 22 22.5
2001 -1 10 33 -20 21.5
2002 10 20 -30 -10 15
2003 20 -10 10 -10 15
2004 8 10 3 -12 7
2005 10 -5 -23 -11 10
run;
data want;
set have;
_count=0;
_temp=0;
array t(*) var:;
do _n_=1 to dim(t);
if t(_n_)>0 then do;_temp+t(_n_);_count+1;end;
end;
MPOS=_temp/_count;
drop _:;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.