计算 0 值的个数

Count number of 0 values

类似于here,我可以计算缺失观察的数量:​​

data dataset;
  input a b c;
cards;
1 2 3
0 1 0
0 0 0
7 6 .
. 3 0
0 0 .
;
run;

proc means data=dataset NMISS N;
run;

但是我怎样才能计算 0 的观测值数量?

如果您想要计算为 0 的观测值的数量,您需要使用 proc tabulateproc freq,并进行频率计数。

如果您有很多值,而您只想要“0/非 0”,那么使用 format.

很容易做到
data have;
  input a b c;
cards;
1 2 3
0 1 0
0 0 0
7 6 .
. 3 0
0 0 .
;
run;

proc format;
  value zerof
  0='Zero'
  .='Missing'
  other='Not Zero';
quit;

proc freq data=have;
  format _numeric_ zerof.;
  tables _numeric_/missing;
run;

类似的东西。显然要小心 _numeric_ 因为那是所有数字变量,如果你有很多它们可能会很快变得混乱......

最容易使用PROC SQL。您必须使用 UNION 来复制 MEANS 输出;

第一个 FROM 的每个部分计算每个变量的 0 值,然后 UNION 将它们叠加起来。

最后一节只计算 DATASET 中的观察次数。

proc sql;
select n0.Variable, 
       n0.N_0 label="Number 0", 
       n.count as N
 from (
   select "A" as Variable,
          count(a) as N_0
      from dataset
      where a=0
   UNION 
   select "B" as Variable,
          count(b) as N_0
      from dataset
      where b=0
   UNION
   select "C" as Variable,
          count(c) as N_0
      from dataset
      where c=0
) as n0,
(
    select count(*) as count
    from dataset
) as n;
quit;

我将此添加为附加答案。它要求你有 PROC IML.

这使用矩阵运算来进行计数。

(ds=0) -- 创建一个矩阵的 0/1 值 (false/true) of values = 0

[+,] -- 对所有列的行求和。如果我们有 0/1 个值,那么这是每列 value=0 的数量。

' -- 运算符是转置。

|| -- 合并矩阵 {0} || {1} = {0 1}

然后我们只打印值。

proc iml;
use dataset;
read all var _num_ into ds[colname=names];
close dataset;
ds2 = ((ds=0)[+,])`;

n = nrow(ds);

ds2 = ds2 || repeat(n,ncol(ds),1);

cnames = {"N = 0", "Count"};
mattrib ds2 rowname=names colname=cnames;

print ds2;
quit;

你可以使用 proc freq 中的级别选项。

proc freq data=dataset levels;
table _numeric_;
run;