如何使用R生成零度的B样条

时间:2019-01-25 16:50:21

标签: r plot spline

我目前正在使用来自软件包bs的R函数splines处理B样条,作为一个图形示例,我想提供一个图形,显示不同程度的样条集之间的差异。

问题是bs仅支持大于0的度。 零度样条曲线仅是由结定义的给定区域的指示函数,但是我真的不知道如何生成它。 这是我到目前为止所做的

x<-seq(0,1,length.out =1000)
    par(mfrow=c(3,1))
    B1<-bs(x,knots = seq(0,1,length.out = 11)[-c(1,11)],Boundary.knots = c(0,1),intercept = T,degree = 1)
    matplot(x,B1,type="l",lty=1,ylim = c(-0.1,1.2),xlab = "",ylab = "")
    abline(v=seq(0,1,length.out = 11),lty=2)
    legend("top", legend ="B-splines of order 2")

    B2<-bs(x,knots = seq(0,1,length.out = 11)[-c(1,11)],Boundary.knots = c(0,1),intercept = T,degree = 2)
    matplot(x,B2,type="l",lty=1,ylim = c(-0.1,1.2),xlab = "",ylab = "")
    abline(v=seq(0,1,length.out = 11),lty=2)
    legend("top", legend ="B-splines of order 3")

    B3<-bs(x,knots = seq(0,1,length.out = 11)[-c(1,11)],Boundary.knots = c(0,1),intercept = T,degree = 3)
    matplot(x,B3,type="l",lty=1,ylim = c(-0.1,1.2),xlab = "",ylab = "")
    abline(v=seq(0,1,length.out = 11),lty=2)
    legend("top", legend ="B-splines of order 4")

这张从Hastie et.al(2017)拍摄的照片基本上就是我所缺少的。 enter image description here

预先感谢

1 个答案:

答案 0 :(得分:1)

根据我的评论,您想要一个给定n点输入向量x的函数,该函数返回一系列n-1个“样条曲线”;其中第 i 个样条线被定义为在其他地方具有1x[i] < x < x[i+1]范围内的值0

我们可以这样做:

x <- seq(0,1,length.out =10)

zero_spline = function(x, xout, n=1000) {
  if (missing(xout)) xout = seq(min(x), max(x), length.out = n)
  zs = data.frame()
  y = numeric(length(xout))
  for (i in 1:(length(x)-1L)) {
    yi = y
    yi[(xout > x[i]) & (xout < x[i+1])] = 1
    zs = rbind(zs, data.frame(xout, yi, interval=i))
  }
  zs
}

zs = zero_spline(x, n=100) 

library(ggplot2)
ggplot(zs, aes(xout, yi, color=factor(interval))) +
  geom_line()

enter image description here