6

Is it there a way to adjust a quadratic spline (instead of a cubic one) to some data?

I have this data and I don't seem to find the appropiate function in R to do this.

natorro
  • 2,793
  • 3
  • 19
  • 16

1 Answers1

11

Expanding just a bit on the comments above, you can use a B-spline basis (implemented in function splines::bs()), setting degree=2 rather than the default 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

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • 1
    A small comment: the quadratic B-spline approach used here will give different results compared to using a quadratic (interpolation) spline. – Lars Lau Raket Jul 16 '15 at 15:45