I have this data set:
x <- c(0, 40, 80, 120, 160, 200)
y <- c(6.52, 5.10, 4.43, 3.99, 3.75, 3.60)
I calculated a linear model using
If your relationship is nonmonotone or if you have multiple predictor values then there can be multiple x-values for a given y-value and you need to decide how to deal with that.
One option that could be slow (and may 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 could use the TkPredict
function from the TeachingDemos
package to eyeball a solution.
Or you could get a fairly quick approximation by generating a lot of predicted points, then feeding them to the approxfun
or splinfun
functions to produce the approximations:
tmpx <- seq(min(x), max(x), length.out=250)
tmpy <- predict(fit, data.frame(x=tmpx) )
tmpfun <- splinefun( tmpy, tmpx )
tmpfun(4)