1
votes
data whatever;
 infile '';
 input price cost;
 <statement>;
run;

In <statement>, what's the difference between using total = sum(total,cost) and total = total + cost ?

2
do you mean total=total+cost; or total+cost; as the second option?Joe
I want to create a running total. Isn't it variable + expression ?zhuoer
It is; just wanted to clarify what you were intending to do (since you didn't explain that in the question).Joe
I was confused by these two statements. First I learnt total+cost and I kept using it. But putting total = sum(total,cost) into it won't lead to an error. So I wonder if they're equivalent.zhuoer
total+cost is faster to type (and avoids having to include retain total;). Otherwise equivalent - like in c++, you can say x=x+1; or x++; equivlanently.Joe

2 Answers

2
votes

You'd probably have trouble with either of those if you actually including it after the input statement.

The information that ProgramFOX posted is correct, but if you're asking about the difference between these three statements, there's a little more to it:

total = sum(total,cost);
total + cost;

The second of these implies a retain total; statement and will also treat nulls as zero. You run into the null problem when you're using this type of expression:

total = total + cost;
2
votes

The differnce can be seen below:

If you want to calculate cumulative total , you should use sum statement.

total = sum(total,cost) /* its a sum function */

total+cost /* its a sum statement,the form is variable+expression */

Here :

"total" specifies the name of the accumulator variable, which contains a numeric value.

1) The variable(total in this case) is automatically set to 0 before SAS reads the first observation. The variable's value is retained from one iteration to the next, as if it had appeared in a RETAIN statement.

2) To initialize a sum variable to a value other than 0, include it in a RETAIN statement with an initial value.

and

"Cost" is an expression

1) The expression is evaluated and the result added to the accumulator variable.

2) SAS treats an expression that produces a missing value as zero.

A sum statement is differ from a sum function in a way that a sum statement retains the value which it has calculated earlier.

However, The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:

retain total 0;
total=sum(total,cost);