* Example: DS2 Matrices and Regression Analysis;
DATA CARS_1;
SET SASHELP.CARS;
I = 1;
KEEP EngineSize Cylinders Horsepower MPG_City MPG_Highway Weight Wheelbase I;
WHERE Cylinders <> .;
RUN;
DATA CARS_2;
SET SASHELP.CARS;
KEEP Length;
WHERE Cylinders <> .;
RUN;
data _null_;
dsid = open('CARS_1');
nobs = attrn(dsid, 'nobs');
call symput('nobs', nobs);
hmnv = attrn(dsid, 'nvars');
call symput ('hmnv', hmnv);
run;
/*
* This does a regression approximation of the hmeq model variable
* MORTDUE using the 'independent' variables CLAGE, CLNO, DELINQ,
* DEROG, NINQ, VALUE and YOJ.
*
* We set up a matrix X with the data for the independent variables,
* and a matrix Y with the dependent data, and then solve for the linear
* coefficients b in y = X * b:
*
* X'*y = X'*X*b
* (X'*X)^-1 * X'*y = b
*/
proc ds2;
data y(overwrite=yes);
DCL INT J;
DCL DOUBLE XR ER;
vararray double s[&hmnv] I EngineSize Cylinders Horsepower MPG_City MPG_Highway Weight Wheelbase;
vararray double m[1] Length;
method init();
dcl package matrix x ym y xtx ti xt bm;
dcl double b[&hmnv];
/* Create the hmeq and mortdue matrices */
x = _new_ matrix(&nobs, &hmnv);
y = _new_ matrix(&nobs, 1);
/* Read the data from the hmeq table */
do j = 1 to &nobs;
set CARS_1;
x.in(s, j);
end;
/*
* x now contains the observations for the variables in hmeq -
* plus a column of 1's for the constant term in the approximation:
*/
/* Read the data from the mortdue table */
do j = 1 to &nobs;
set CARS_2;
y.in(m, j);
end;
/*
* y is now a column vector containing the known values of MORTDUE
*/
/* Make sure the row count matches */
xr = x.rows();
er = y.rows();
if (xr ne er) then do;
put 'invalid data';
stop;
end;
/* Compute ti = (X'*X)^-1 */
xt = x.trans();
xtx = xt.mult(x);
ti = xtx.inverse();
/* Compute ym = X'*y */
ym = xt.mult(y);
/* Compute b = (X'*X)^-1 * X'y */
bm = ti.mult(ym);
/*
* The b vector is equivalent to the parameter estimate from
*/
bm.toarray(b);
do i = 1 to &hmnv;
put b[i];
end;
end;
enddata;
run;
quit;
PROC REG DATA = SASHELP.CARS;
MODEL Length = EngineSize Cylinders Horsepower MPG_City MPG_Highway Weight Wheelbase;
WHERE Cylinders NE .;
RUN;
QUIT;
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9.
Lock in the best rate now before the price increases on April 1.