Return to Archive

SAS Tip of the Month
January 2009

It is sometimes necessary to add a number of variables in a record and create a variable containing the total. How can we go about it.

Lets say we have the following data in a dataset:

   SubjectID  x1  x2  x3
      101     1   2   3
      102     3   4   6

To get the total of x1, x2 and x3 it is possible to do the following:

   Sumx = sum(x1,x2,x3);

However, what if we not only wanted the SUM, but also the MEAN, MIN and MAX values? We would have to write four references to the variables and would appear like:

   Sumx = sum(x1,x2,x3);
   Meanx = mean(x1,x2,x3);
   Minx = min(x1,x2,x3);
   Maxx = max(x1,x2,x3);

But what if a variable x4 came along, all four lines will have to be amended. Another way is to put the variables into an array reference and use OF processing, as the following example illustrates:

   array z{*} x1 x2 x3;
   Sumx = sum(of z{*});
   Meanx = mean(of z{*});
   Minx = min(of z{*});
   Maxx = max(of z{*});

Thus if variable x4 suddenly came into the mix then the only thing that would change is the array reference, i.e.

   array z{*} x1 x2 x3 x4;

For this example, I have used the variables x1, x2 and x3, and have one feature – they all start with the letter ‘x’. Due to this feature it is possible to use the following code when doing the function calls, as the following example illustrates:

   Sumx = sum(of x:);

Try it and see.

________________________________
Updated January 1, 2009