如何计算平均值并除以仅可用值而不包括缺失值

时间:2019-05-08 10:25:53

标签: sas

下面有一个数据集示例,我想计算每个客户的平均月薪,但只将我的平均值除以捕获金额值的月份数。

data have;
infile cards truncover;
input   ID  :$10.  name  :$10.  amount  :10. month :$10. ;
cards;
A1 John 2000   Jan
A1 John          Feb
A1 John 300 Mar
A1 John  2000  Apr
A1 John 300   May
A1 John 200 Jun
A2 Sam       Jan
A2 Sam       Feb
A2 Sam 100 Mar
A2 Sam 300 Apr
A2 Sam 300 May
A2 Sam 300 Jun
A3 Paul 1000 Jan
A3 Paul 1000 Feb
A3 Paul 1000 Mar
A3 Paul      Apr
A3 Paul      May
A3 Paul 1000 Jun
A4 Phil 300 Jan
A4 Phil 300 Feb
A4 Phil 300 Mar
A4 Phil 300 Apr
A4 Phil 300 May
A4 Phil 300 Jun
;

我要存档的是,如果我们查看ID = A1,那么6个值中就有5个值,我想做(2000 + 300 + 2000 + 300 + 200)/ 5 =吗?对于ID = A2,由于只有4个缺失,因此将被4除

3 个答案:

答案 0 :(得分:1)

花时间了解SAS MEANS过程和BY声明。

Proc means data = have;
  by ID;
  var amount;
run;

答案 1 :(得分:0)

SQL AVG聚合函数完全满足您的要求

proc sql;
  create table want as
    select ID,name,AVG(amount) from have group by ID,name;
quit; 

答案 2 :(得分:0)

Proc sql;
     create table want as 
     select distinct ID,
     average(amount) as Calculation 
     from have
     group by ID;
quit;