I am running a quantile regression model on some data with one natural cubic spline, which needs to be monotonically decreasing (because it cannot physically increase at any point). To start with I used the ns()
function from the splines
package to achieve this but quickly found that it won't do (unsurprisingly). So I found the function mSpline
from the package splines2
which is supposed to fit monotonic splines, but it also does not work. Below is an example of the two functions and how they fail on mtcars
.
How can I achieve my goal of obtaining monotonically decreasing splines either with my approach or some other approach?
Bonus points if additional variables can be added to the model, which are not splined.
library(quantreg)
mod=rq(mpg~ns(hp,df=3),data=mtcars,tau=0.99)
mod=rq(mpg~mSpline(hp,df=3),data=mtcars,tau=0.99) #monotone
preds=predict(mod)
plot(mtcars$mpg~mtcars$hp)
points(preds~mtcars$hp,col=2,cex=1,pch=16)