Haroon Rashid Haroon Rashid - 1 month ago 8
R Question

Ensure knots in spline regression are placed at correct positions

I have time-series data as:

library(xts)
library(splines)
set.seed(123)
seq <- seq(as.POSIXct("2015-09-01"),as.POSIXct("2015-09-01 23:59:59"), by = "hour")
ob <- xts(rnorm(length(seq),150,5),seq))


The object
ob
is hourly time-series object. Now, I want to do spline regression over it. I want to place knots at 7 A.M and 4 P.M.
Does the following statement in
R
ensure this

ns(ob,knots = c(7,16)) # 7 corresponds to 7 AM and 16 corresponds to 4 PM


Also, how should I cross check that knots are placed at the said times?

Answer

You are sort of on the wrong track. It seems you want to regress observation on time, so you should really feed time index rather than observations ob to ns.

y <- as.vector(ob)    ## observations
x <- 1:24    ## 24 hourse

Then consider a model:

y ~ ns(x, knots = c(7, 16))

As you can see, there is really no need to use "xts" object here.


ns generates a design matrix. Have a check on

X <- ns(x, knots = c(7, 16))

You will see attributes:

#attr(,"degree")
#[1] 3
#attr(,"knots")
#[1]  7 16
#attr(,"Boundary.knots")
#[1]  1 24
#attr(,"intercept")
#[1] FALSE
#attr(,"class")
#[1] "ns"     "basis"  "matrix"

The "knots" field gives you information on location of internal knots.