I'm trying to fit a smooth spline to what looks like data with two peaks. First, I fit a smooth spline to my data to identify the potential position of the knots.
library(npreg)
library(splines)
library(mgcv)
x <- c(20.70, 20.44, 20.58, 21.02, 19.90, 6.20, 8.20, 6.92, 5.86, 6.44, 6.34, 8.48, 8.46, 9.00, 9.06, 9.00, 9.06, 17.98, 18.42, 19.18, 22.88, 24.16,20.20, 23.50)
y <- c(19.884208, 12.772114, 12.932944, 5.016790, 11.405843, 3.310724, 3.950049, 3.641571, 4.073783, 4.616096, 3.425635, 7.773548, 7.498084, 9.474213, 6.162779, 11.041210, 12.618555, 6.287967, 4.286919, 3.242361, 7.571644, 3.379709, 5.274434, 8.8258)
data = data.frame(x,y)
fit_spline <- smooth.spline(x,y)
plot(x,y)
lines(fit_spline,lwd=2,col="purple")
Then, I wanted to run a regression using the gam function where I can specify the position of the knots. I get an error that says Error in smooth.construct.bs.smooth.spec(object, dk$data, dk$knots) : there should be 7 supplied knots I am not sure where it's drawing this number. If I supply 7 knots, it says it needs 13 knots...and the same erorr gets repeated. I am unclear on how to proceed.
myfit <- gam(y ~ s(x, bs = 'bs', k = 3),
knots = list(x = c(1,5,20)))
my_knots <- myfit$smooth[[1]]$xp
plot(x, y, col= "grey", main = "my knots");
lines(x, myfit$linear.predictors, col = 2, lwd = 2)
abline(v = my_knots, lty = 2)
