Simple SAS calculation

608 views Asked by At

I have a data set with three columns: Names, ColA and ColB. There's a number of rows for each name, and for each name I need to subtract B from A, and make a new column get the remaining value of the differece between A and B:

Names  ColA    ColB   NewColA
  x      100       5      95
  x      100      20      75
  x      100      10      65 

Is this possible? I've tried using IF-Then statements, Do-While and considered a macro but my head is still stuck in Excel/VBA mode so I'm not sure how to do it?

1

There are 1 answers

6
Tacio Medeiros On BEST ANSWER

Your question is very similar to doing a running total with a by grouping. An example of that is found here: http://support.sas.com/kb/24/649.html

The secret is using the "first" implicit variables.

data out;
    set [replace with your input dataset]; 
    by names;
    retain newColA;
    if first.names then newcola=cola;
    newcola = newcola - colb;
run;

[edit] I forgot the retain statement. Here goes an example using the fish dataset from sashelp. (Although it doesn't make sense doing that there.)

First off, the dataset must be sorted. If yours is already you can go straight to the data step.

proc sort data = sashelp.fish(where=(Weight ne .) drop=Length1-Length3) out = fish nodupkey force;
    by species weight height;
run;

data out;
    set fish;
    by species;
    retain newColA;
    if first.species then newColA  = weight;
    newColA = newColA - height;
run;