Pablo Rodriguez
Pablo Rodriguez

Reputation: 27

SAS - count within arrays

In a data step in which I have defined an array I can use the sum function, but the count function doesn't work. How can I count the number of values that are not zero within an array?

SUM_ARRAY = sum(of A1-A20); - Works
COUNT_ARRAY = count(of A1-A20);  Yields the following error: "The COUNT function call has too many arguments"

Upvotes: 1

Views: 935

Answers (2)

Joe
Joe

Reputation: 63424

COUNT can be coerced to do this, if your data is agreeable. I'm not sure it's better than the loop operation timewise or structurally, but it's at least an interesting solution.

Basically we delimit the data by ; including starting and ending it with the delimiter, then count the number of ;0;, and subtract from the total.

data _null_;
  call streaminit(7);
  array a[20];
  do _i = 1 to 20;
    a[_i] = max(0,rand('Uniform')-0.3);
  end;
  put a[*]=;
  nonzero = dim(a) - count(';'||catx(';',of a[*])||';',';0;');
  put nonzero=;
run;

Upvotes: 1

Reeza
Reeza

Reputation: 21264

The correct function instead of COUNT is either N, DIM, or HBOUND. Unfortunately none will count specific values, only exclude missing values.

Looping through results is one way to count non 0s.

Array _a(*) a1-a20;
Count0 = 0;
Do I = 1 to dim(_a);
   If _a (I) ne 0 then count0 = count0 + 1;
End;

Upvotes: 1

Related Questions