data whatever;
infile '';
input price cost;
<statement>;
run;
In <statement>
, what's the difference between using total = sum(total,cost)
and total = total + cost
?
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;
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);
total=total+cost;
ortotal+cost;
as the second option? – Joevariable + expression
? – zhuoertotal+cost
and I kept using it. But puttingtotal = sum(total,cost)
into it won't lead to an error. So I wonder if they're equivalent. – zhuoertotal+cost
is faster to type (and avoids having to includeretain total;
). Otherwise equivalent - like in c++, you can sayx=x+1;
orx++;
equivlanently. – Joe