Home > database >  How to use sum function in SAS
How to use sum function in SAS

Time:12-08

I think there're other ways to sum of all cells. I'd just like to learn how to use sum function. Please give me some advice about "sum(y)" following program in SAS.

data dt00;
 input X Y @@;
 cards;
 1 3 2 5
;
run;

data dt01;
 set dt00;
 z x sum(y);
run;

CodePudding user response:

Summing along row - sum and arrays.

Using the sum function:

data want;
    set dt00;
    sum=sum(x, y);
run;

You could also use sum=sum(of _numeric_); - this will sum all numeric columns in case too many to list.

Using arrays:

data want;
    set dt00;
    array s {*} _numeric_;
    sum=sum(of s[*]);
run;

Summing along column - here we are only interested in the total sum of the column, so we select the last row. You can do this with the combination of the end= option in the set statement and the if statement.

data want;
    set dt00 end=eof; 
    sum_x   x;
    sum_y   y;
    
    if eof then output;
    keep sum:;
run;

In case you have a lot of columns I would advise you to compute the columns total using other SAS procedures (e.g. using the means procedure).

proc means data=dt00 noprint;
    var _numeric_;
    output out=want(drop=_type_ _freq_) sum= / autoname;
run;

Summing all cells - here we use the same trick as for summing along column as we are only interesting in the total sum of all cell.

data want;
    set dt00 end=eof;
    sum   x   y;

    if eof then output;
    keep sum;
run;

The sum statement sum x y implies that the sum variable is automatically retained and that all missing values are considered as 0.

Put simply, this is the equivalent of

data want;
    set dt00 end=eof;
    retain sum;
    sum = sum(sum,x,y);

    if eof then output;
    keep sum;
run;
  • Related