SAS Data Integration Studio, DataFlux Data Management Studio, SAS/ACCESS, SAS Data Loader for Hadoop and others

Count within arrays

Occasional Contributor
Posts: 5

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"

Super User
Posts: 5,081

Re: Count within arrays

The COUNT function is intended for character strings.  Perhaps you are thinking of the N function?  (If not, what are you trying to accomplish?)

Super User
Posts: 10,487

Re: Count within arrays

I don't even see the array mentioned in the question.


I would likely start with something like this:

array values a1-a20;
sum_array = sum(of values(*));
do i= 1 to dim(values);
   Count_array= sum(count_array,(values[i] ne 0));

However this will count values that are missing as well. Is that the desired behavior?


Valued Guide
Posts: 505

Re: Count within arrays

I don't think it is possible?

Here is what I consider minimal code:

data tst;
array values a1-a5 (10 0 23 15 43);
do over values;
 cnt + (values ne 0);

Up to 40 obs WORK.TST total obs=1

Obs    A1    A2    A3    A4    A5    ARRAY    CNT

 1     10     0    23    15    43      91      4

Regular Contributor
Posts: 244

Re: Count within arrays

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);
  put a[*]=;
  nonzero = dim(a) - count(';'||catx(';',of a[*])||';',';0;');
  put nonzero=;


(This was cross-posted to/from Stack Overflow:

Ask a Question
Discussion stats
  • 4 replies
  • 1 like
  • 5 in conversation