Yet Another Blog in Statistical Computing

I can calculate the motion of heavenly bodies but not the madness of people. -Isaac Newton

How to Construct Piecewise Linear Spline in SAS

options nocenter;

data tmp1;
  do i = 1 to 5000;
    x = ranuni(1);
    y = x + rannor(1) * 0.5;
    if x >= 0.3 then y = y + 6 * (x - 0.3);
    if x >= 0.6 then y = y - 10 * (x - 0.6);
    output;
  end;
run;
 
*** Manually Construct Piecewise Spline ***;
data tmp2;
  set tmp1;
  x1 = x;
  x2 = max(x - 0.3, 0);
  x3 = max(x - 0.6, 0);
run;

proc reg data = tmp2;
  model y = x1 - x3;
run;  
quit;
/*                   Parameter       Standard
Variable     DF       Estimate          Error    t Value    Pr > |t|

Intercept     1        0.02627        0.02432       1.08      0.2801
x1            1        0.81570        0.11576       7.05      <.0001
x2            1        6.29682        0.18477      34.08      <.0001
x3            1      -10.19025        0.14870     -68.53      <.0001
*/
    
*** Automatically Construct Piece Spline ***;
proc transreg data = tmp1 ss2;
  model identity(y) = pspline(x / knots = 0.3 0.6 degree = 1);
run;
/*                                   Type II
                                      Sum of       Mean
Variable        DF    Coefficient    Squares     Square    F Value    Pr > F    Label

Intercept        1       0.026272       0.28       0.28       1.17    0.2801    Intercept
Pspline.x_1      1       0.815702      12.12      12.12      49.65    <.0001    x 1      
Pspline.x_2      1       6.296817     283.50     283.50    1161.34    <.0001    x 2      
Pspline.x_3      1     -10.190247    1146.47    1146.47    4696.43    <.0001    x 3      
*/

Advertisements

Written by statcompute

April 22, 2013 at 11:10 pm

%d bloggers like this: