Suppose I have data x = (x_1,...,x_n). I would like to create a basis matrix in R whose (i,j)th entry is B_j(x_i) - B_j(0), where B_j(.) is the jth cubic B-spline basis function. Is this possible to implement?
Using the bs function from the splines package gives me the basis matrix with entries B_j(x_i). Note that the actual value B_j(0) depends on my data, but I am not looking for this value. I just want my basis functions B_j(x) to evaluate to 0 at x = 0, which I am trying to do by replacing B_j(x) with B_j(x) - B_j(0).
For more context, check https://stats.stackexchange.com/q/662217/464154.
This creates the basis and then subtracts the value at x==0 from each row.
x <- -50:50
sp <- splines::bs(x, 5)
zeroval <- predict(sp, newx = 0)
sp[] <- sweep(sp, MARGIN = 2, FUN = "-", STATS = zeroval)
matplot(x, sp, type = "l", lty = 1)
You could create a wrapper function that does this:
bsz <- function(...) {
sp <- splines::bs(...)
zeroval <- predict(sp, newx = 0)
sp[] <- sweep(sp, MARGIN = 2, FUN = "-", STATS = zeroval)
return(sp)
}