首页 > 解决方案 > SAS:对表列的子集求和(多次)

问题描述

(我是 SAS 新手,我很纠结按列做事情的难度,这在“普通”语言中很容易。如果这是非常基本的,请多多包涵。)

我有一个值typea1-a10b1-b10的表,我想(对于每个N )找到aN为正的那些行的bN总和。我可以一次做一个变量,例如:

proc sql;
create table work.test1 as
    select type, b1
    from work.table
    where (a1 >0);
run;

然后对所有这些表求和,然后合并它们,但这将是很多代码和一些小问题。有没有一种很好且紧凑的方法来做到这一点?

编辑:我想要的输出是一个值类型sum1-sum10的表,其中sumN是上述总和。

样本数据:

type | a1 | a2 | ... | b1 | b2 | ...
------------------------------------
 cat   10   14   ...   1     2   ...
 cat   -5    3   ...   1     1   ...
 dog   35   -1   ...   9     3   ...
 dog    9    2   ...  0.5    1   ...

期望的输出:

type | sum1 | sum2 | ...
------------------------
 cat    1      3     ...
 dog   9.5     1     ...

因此,对于每种类型N将同一行上的aN为正的那些bN相加。

标签: sas

解决方案


这是一种proc summary方法。这不像数组方法那么直接,但它更容易推广到您可能感兴趣的其他统计数据。

data have; 
input type $ a1   a2   b1  b2  ; 
datalines;
cat    10   14   1    2
cat    -5    3   1    1
dog    35   -1   9    3
dog     9    2   0.5  1
;
run;

/*Create a view of the dataset with suitable weight columns*/
data t_have / view = t_have;
  set have;
  array a[*] a1-a2;
  do i = 1 to dim(a);
    a[i] = a[i] > 0;
  end;
run;

/*Use proc summary to sum across rows*/
proc summary nway data = t_have;
  class type;
  var b1 /weight=a1; /*You could macro-ise this bit to avoid excessive repetition*/
  var b2 /weight=a2;
  output out= want(drop=_:) sum= mean= /autoname;
run;

推荐阅读