二次样条

时间:2012-10-17 00:40:23

标签: r

有没有办法将二次样条(而不是立方样条)调整为某些数据?

我有这些数据,我似乎没有在R中找到合适的功能来执行此操作。

1 个答案:

答案 0 :(得分:10)

在上面的评论中稍微扩展一下,您可以使用B样条基础(在函数splines::bs()中实现),设置degree=2而不是默认degree=3

library(splines)

## Some example data
set.seed(1)
x <- 1:10
y <- rnorm(10)

## Fit a couple of quadratic splines with different degrees of freedom
f1 <- lm(y ~ bs(x, degree = 2))  # Defaults to 2 - 1 = 1 degree of freedom
f9 <- lm(y ~ bs(x, degree = 2, df=9))

## Plot the splines
x0 <- seq(1, 10, by = 0.1)
plot(x, y, pch = 16)
lines(x0, predict(f1, data.frame(x = x0)), col = "blue")
lines(x0, predict(f9, data.frame(x = x0)), col = "red")

enter image description here