Simon Wood
2015-Jun-01 21:00 UTC
[R] How to make new predictions from a GAM with a spline forced through the origin
Hi Gavan, After running the code in your message, do something like this... xp <- c(.2,.3) ## x values for prediction Xp <- PredictMat(sm,data.frame(x=xp))[,-3] ## prediction matrix yp <- predict(b,list(X=Xp,off=rep(.6,2))) ## call predict.gam points(xp,yp,col=2) ## plot points ... hope that's clear enough, let me know if not. best, Simon On 29/05/15 13:12, Gavan McGrath wrote:> Hi, > > I?m followed an example to fit a GAM with a spline forced through a point, i.e. (0,0). This works fine from one of Simon?s examples however when it comes to making a prediction from a new set of x values I?m a bit stumped. > > In the example below a smooth term is constructed and the basis and penalties at x=0 are removed then the gam is fitted to a spline basis matrix X using spline penalties. > > Can someone suggest a way that I can make predictions at new x values based on the gam b below. > > > Here is Simon Wood's example: > > library(mgcv) > set.seed(0) > n <- 100 > x <- runif(n)*4-1;x <- sort(x); > f <- exp(4*x)/(1+exp(4*x));y <- f+rnorm(100)*0.1;plot(x,y) > dat <- data.frame(x=x,y=y) > > ## Create a spline basis and penalty, making sure there is a knot > ## at the constraint point, (0 here, but could be anywhere) > knots <- data.frame(x=seq(-1,3,length=9)) ## create knots > ## set up smoother... > sm <- smoothCon(s(x,k=9,bs="cr"),dat,knots=knots)[[1]] > > ## 3rd parameter is value of spline at knot location 0, > ## set it to 0 by dropping... > X <- sm$X[,-3] ## spline basis > S <- sm$S[[1]][-3,-3] ## spline penalty > off <- y*0 + .6 ## offset term to force curve through (0, .6) > > ## fit spline constrained through (0, .6)... > b <- gam(y ~ X - 1 + offset(off),paraPen=list(X=list(S))) > lines(x,predict(b)) > > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Simon Wood, Mathematical Science, University of Bath BA2 7AY UK +44 (0)1225 386603 http://people.bath.ac.uk/sw283