Ever been confused by the result when trying to add numeric values using a plus (+) operator? Maybe you discovered the Sum() function to get around the problem but never really understood why it worked. In this blog post, I explain the Add() function, plus (+) operator, and the Sum() function to help you get the results you need from your script or column formula.
Let’s start with the Add() function. Did you know that plus (+) is the symbolic representation of the Add() function? It is! That means that the following two expressions are exactly the same:
1 + 2; //Returns 3
Add( 1, 2 ); //Returns 3
The Add() function and the plus operator add values to calculate a total value. The arguments can be numbers, matrices or lists of numbers.
But what if one of the values is a numeric missing (.)? The Add() function will return missing if any of the arguments is a missing value.
In the previous example, the result was 3 for either expression. Building on that, if a missing value was one of the arguments, then it would return missing, rather than 3.
1 + . + 2; //Returns missing
Add( 1, ., 2 ); //Returns missing
So how do you still obtain a total value excluding the missing values? This is where the Sum() function comes in. The Sum() function will also add values to calculate a total value, however, it ignores missing values.
Below is the syntax for the Sum() function. Notice the arguments are separated by commas and the total value of all non-missing arguments is calculated.
Sum( 1, ., 2 ); //Returns 3
Can Sum() ever return missing? Well, yes, it can. When the argument(s) supplied to the Sum() function are all missing values, the result will also be missing. In this example, the value of both x and y is missing.
x = y = .;
Sum( x, y ); //Returns missing
And don’t get tripped up thinking that you can use the plus operator to specify the arguments.
Sum( 1 + . + 2 ); ); //Returns missing
When you do that, JMP sees this as one argument that uses the Add() function. And remember that the Add() function returns missing when any of the arguments is a missing value:
Sum( Add( 1, ., 2 ) ); //Returns missing
Which is essentially the same as this:
Sum( . ); //Returns missing
If you changed that example to include two arguments, such as:
Sum( 100, 1 + . + 2 ); //Returns 100
The result is 100 because the arguments are 100 and missing, as in:
Sum( 100, . ); //Returns 100
I hope this helps to clarify the uses of Add(), plus (+), and Sum().