If your relationship is non-monotonic or you have several predictor values, then for a given y value there may be several x values, and you need to decide how to deal with it.
One option, which can be slow (and can be the method used in the other packages mentioned), is to use the uniroot function:
x <- runif(100, min=-1,max=2) y <- exp(x) + rnorm(100,0,0.2) fit <- lm( y ~ poly(x,3), x=TRUE ) (tmp <- uniroot( function(x) predict(fit, data.frame(x=x)) - 4, c(-1, 2) )$root) library(TeachingDemos) plot(x,y) Predict.Plot(fit, 'x', data=data.frame(x=x), add=TRUE, ref.val=tmp)
You can use the TkPredict function from the TeachingDemos package to find a solution.
Or you could get a pretty fast approximation by creating many predicted points and then passing them to the approxfun or splinfun to create the approximations:
tmpx <- seq(min(x), max(x), length.out=250) tmpy <- predict(fit, data.frame(x=tmpx) ) tmpfun <- splinefun( tmpy, tmpx ) tmpfun(4)
Greg snow
source share