Skip to content
Prev 318563 / 398503 Next

solving x in a polynomial function

You can avoid doing the algebra by using uniroot() to numerically find where
the predicted value hits your desired value.  E.g.,

  > fit <- lm(a ~ poly(b, 4))
  > invertFit <- function(a){
  +     stopifnot(length(a)==1)
  +     uniroot(function(b)predict(fit, newdata=list(b=b))-a, interval=range(b))$root
  + }
  > invertFit(5)
  [1] 3.506213
See that it works with a plot:
  > plot(b, a)
  > btmp <- seq(min(b), max(b), len=129)
  > lines(btmp, predict(fit, newdata=list(b=btmp)))
  > abline(h=5, v=invertFit(5))
  > abline(h=7, v=invertFit(7))

uniroot will not tell you if there is a problem due to the fit being nonmontonic, so
check the plot.  (E.g., try lm(a ~ poly(b, 8)).)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com