1 min read

Calculating Covariance by SAS, A Brutal Way

It was very disappointed that there is only one built-in method to calculate covariance in Base SAS: that’s in PROC CORR (while you can also do it in SAS/IML, of course):

sascorr

The following is a quick-and-dirty way to get a function like %COV:

%macro COV(data, var1,var2);
    %local _cov;
    %let rc = %sysfunc(dosubl(%str(

    ods select none ;
    ods output cov=_cov;

    proc corr data=&data  cov ;
    var &var1 &var2 ;
    run;

    ods select all;

        proc sql noprint;
    select &var2 into :_cov
    from _cov  (obs=1)
    ;
    drop table  _cov;
    quit
    )));
    &_cov
%mend COV;

You can use it in macro variable assignment:

%let cov = %COV(sashelp.iris,SepalLength,SepalWidth);

or in a data step:

data iris;
    set sashelp.iris;
    cov = %COV(sashelp.iris,SepalLength,SepalWidth);
run;

or in PROC SQL:

proc sql;
    create table iris2 as
    select *,
    %COV(sashelp.iris,SepalLength,SepalWidth) as cov
    from sashelp.iris;
quit;

One line conclusion: I LOVE Dosubl and hope this Dosubl also inspires your programming!