sascolumn-sum

Vertical column summation in sas


I have the following piece of result, which i need to add. Seems like a simple request, but i have spent a few days already trying to find the solution to this problem.

Data have:

Measure   Jan_total   Feb_total
Startup      100         200
Switcher     300         500

Data want:

Measure   Jan_total   Feb_total
Startup      100         200
Switcher     300         500
Total        400         700

I want individually placed vertical sum results of each column under the respective column please.

Can someone help me arrive at the solution for this request, please?


Solution

  • To do this in data step code, you would do something like:

    data want;
      set have end=end;       * Var 'end' will be true when we get to the end of 'have'.;
      jan_sum + jan_total;    * These 'sum statements' accumulate the totals from each observation.;
      feb_sum + feb_total;
      output;                 * Output each of the original obbservations.;
      if end then do;         * When we reach the end of the input...;
        measure = 'Total';    * ...update the value in Measure...;
        jan_total = jan_sum;  * ...move the accumulated totals to the original vars...;
        feb_total = feb_sum;
        output;               * ...and output them in an additional observation.
      end;
      drop jan_sum feb_sum;   * Get rid of the accumulator variables (this statement can go anywhere in the step).;
    run;
    

    You could do this many other ways. Assuming that you actually have columns for all the months, you might re-write the data step code to use arrays, or you might use PROC SUMMARY or PROC SQL to calculate the totals and add the resulting totals back using a much shorter data step, etc.