# SAS Math Difference between two tables

Have two data their variables name and layout are exactly the same

``````data data1;
input var\$ val1 val2 val;
datalines;
A 0 8 8
B 9 8 7
C 7 2 3
;

data data2;
input var\$ val1 val2 val;
datalines;
A 0 7 8
B 9 8 7
C 5 2 3
;
``````

Want the math diff in each numeric cell.Look for elegant and smart ways. The really data set has more variables and columns.

``````data want;
input var\$ val1 val2 val;
datalines;
A 0 1 0
B 0 0 0
C 2 0 0
;
`````` On Best Solutions
``````proc compare base=data1 compare=data2 out=diff outdif noprint;
id var;
run;
``````  On

Assuming that the data structures are exactly the same and that both dataset have the exact same number of observations in the same relative order you could do this.

Basically copy the data from the first dataset into a temporary array and then read the data from the second dataset and perform the subtraction.

``````data want;
array _temp  _temporary_ ;
set data1 ;
array _x _numeric_;
do _n_=1 to dim(_x);
_temp[_n_]=_x[_n_];
end;
set data2 ;
do _n_=1 to dim(_x);
_x[_n_] =_temp[_n_]-_x[_n_];
end;
run;
``````

Make sure the size of the temporary array is large enough. Making too large will not hurt anything.

You can change the `_numeric_` variable list to a more specific list of variables if you don't want to calculate the difference for all of the numeric fields. Any variable not included in the array will have the values read from the second dataset.