semibruin semibruin - 4 months ago 18
R Question

extract matrix from bs (b spline) function output in R

Let

x = c(1, 2, 3)
be a vector. I use
bs
function in the
splines
package of
R
to generate a matrix of B splines evaluated at
x
.

require(splines)
x <- c(1, 2, 3)
bs.x <- bs(x, knots = c(1.5, 2.5))


The output
bs.x
is as follows,

1 2 3 4 5
[1,] 0.00000000 0.0000000 0.0000000 0.00000000 0
[2,] 0.05555556 0.4444444 0.4444444 0.05555556 0
[3,] 0.00000000 0.0000000 0.0000000 0.00000000 1
attr(,"degree")
[1] 3
attr(,"knots")
[1] 1.5 2.5
attr(,"Boundary.knots")
[1] 1 3
attr(,"intercept")
[1] FALSE
attr(,"class")
[1] "bs" "basis" "matrix"


Clearly, besides the basis matrix,
bs.x
has other attributes. My question is how to get rid of these attributes. I need to do this, because ultimately, I need to run
Matrix(bs.x)
, which throws me the following error message.

Error in as(x, "matrix") :
internal problem in as(): “bs” is(object, "matrix") is
TRUE, but the metadata asserts that the 'is' relation is FALSE


I guess this is because
matrix
is one of the classes that
bs.x
belongs to. At this moment, I do the following dumb thing.

bs.x <- matrix(as.numeric(bs.x), nr = nrow(bs.x))


Is there a better alternative? Thanks in advance.

Answer

Not a whole lot better, but

attributes(bs.x) <- attributes(bs.x)["dim"]

seems to work. (Reassigns the attributes of bs.x to be only the dim attribute.)