2

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!

Matifou
  • 2,699
  • 14
  • 25
  • 1
    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](https://www.r-bloggers.com/estimating-continuous-piecewise-linear-regression/) link seems convenient. For power-basis, the `fda` package has some functionality that might be handy but I have never really tried it... – usεr11852 Feb 24 '19 at 00:28
  • 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! – Matifou Feb 24 '19 at 00:37

1 Answers1

0

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.

Gi_F.
  • 1,011
  • 1
  • 7
  • 11