3
$\begingroup$

I want to replicate in R figures 5.1 and 5.2 of the Elements of Statistical learning (Hastie et al), . The authors show how to derive a cubic splines. These splines are not in the B-basis.

Can I use package splines to do this (I want to use it instead of manual coding, hoping the former will be more efficient) ? It seems bs() and ns() will only create b/natural splines. Is there a way to obtain simple splines? These would be (equation 5.3 in ESL):

  • $h_1(x) = 1$, $h_2(x) = x$
  • $h_3(x) = x^2$, * $h_4(x) = x^3$
  • $h_5(x) = (x-\xi)^3_+$,

Thanks!

$\endgroup$
2
  • 1
    $\begingroup$ You can always create the piecewise linear quite easily manually but defining the segments and then defining two dummy variables for each segment, one for the intercept and one for the slope. Regarding the continuous piecewise linear, this link seems convenient. For power-basis, the fda package has some functionality that might be handy but I have never really tried it... $\endgroup$
    – usεr11852
    Commented Feb 24, 2019 at 0:28
  • $\begingroup$ Thanks! My question is specifically about splines, as I hope it will be more efficient and flexible. But the code you linked is a nice alternative! $\endgroup$
    – Matifou
    Commented Feb 24, 2019 at 0:37

1 Answer 1

1
$\begingroup$

I do not know if you are still interested in this. You can obtain the spline functions you mention in your question with few lines of code

tpower = function(x, t, p) (x - t) ^ p * (x > t)

tpf_bases = function(x, knots, deg = 3)
{    
    X = matrix(0, nrow = length(x), ncol = deg)
    for(i in 1:deg) X[, i] = x^i
    X = cbind(1, X)

    Z = outer(x, knots, tpower, deg)
    Z = Z * (Z > 0)
    return(list(X = X, Z = Z))

}

x     = 1:10
bases = tpf_bases(x, deg = 3, knots = c(2, 3, 4))
X     = bases$X # x^0, x^1,...
Z     = bases$Z # Truncated power part

If you are interested also in the relationship between B-splines and truncated power bases, you could give a look to this discussion: Splines - basis functions - clarification

If you are also interested in how to fit penalized splines using the bases just defined, you can give a look here: Representing a GAM with truncated power basis as a mixed model

Hope this helps a bit and replies (at least partially) to the original question.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.