Search code examples
sassummary

Counting number of different fields in SAS


I have a table in SAS (using WPS Workbench) that looks like this.

ID   Band_1  Band_2 Band_2 ... Band_160
1    Y       Y      N          Y
2    N       N      N          N
3    Y       N      N          Y
4    N       Y      Y          Y
..
200  Y       N      N          Y

I want to summarise the table as follows: For each Band, I want a count of the number of Y and N values, with the table transposed (optional).

So down the left will consist of each band, and across the top will be a Y count and an N count. Or the bands can be across the top I don't mind.


Solution

  • Array processing is one (of several) ways to obtain your summary counts.

    data have;
      do id = 1 to 200;
        array band(160) $1;
        do _n_ = 1 to dim(band);
          band(_n_) = substr('YN', 1+(ranuni(123)<0.4));
        end;
        output;
      end;
    run;
    
    data want1(keep=column yes_n no_n);
      set have end=last;
      array band(160);
      array Yes(160) _temporary_ (160*0);
      array No(160) _temporary_ (160*0);
    
      * accumulate counts;
      do _n_ = 1 to dim(band);
        if band(_n_) = 'Y' then Yes(_n_)+1; else
        if band(_n_) = 'N' then No(_n_)+1;
      end;
    
      * emit counts;
      if last then
        do _n_ = 1 to dim(band);
          column = vname(band(_n_));
          yes_n = Yes(_n_);
          no_n = No(_n_);
          output;
        end;
    run;
    

    The same 'want' data could be obtained from other techniques that use

    • Hash object
    • Transpose / Report
    • Transpose / Tabulate
    • Transpose / Freq