5

I need to predict the corresponding x value of a new y value using a fitted model.

The usual case of predicting the y value from a new x value is straightforward by using the predict function, but I cannot figure out how to do the reverse.

For cases with multiple x solutions, I wish to obtain all solutions within the range of x values, i.e. 1-10. And the new y will always be within the range of y values used for fitting the model.

See below for an example code, where I need to find new x value (new_x).

x = seq(1:10)
y = c(60,30,40,45,35,20,10,15,25,10)

fit = lm(y ~ poly(x, 3, raw=T))

plot(x, y)
lines(sort(x), predict(fit)[order(x)], col='red') 

example plot

new_y = 30
new_x = predict(fit, data.frame(y=new_y)) #This line does not work as intended.

Edit 1: Inversed fitting

Fitting the inversed relationship will not give the same model, since we get a different model/fitted line.

rev_fit = lm(x ~ poly(y, 3, raw=T))

plot(x, y)
lines(sort(x), predict(fit)[order(x)], col='red') 
lines(predict(rev_fit)[order(y)], sort(y), col='blue', lty=2) 

example plot 2

cylim
  • 542
  • 1
  • 6
  • 15
  • Regarding your comment on the lack of symmetry, you come use pca to create a line where there is symmetry (i.e. you no value of one dimension, you know the othet). You could also crete tw separate regressions (the reason for the lack of symmetry is due to regression to the mean). Curious if there are other ideas /approaches here though. – Bryan Shalloway Jan 22 '21 at 05:23
  • See here: https://stats.stackexchange.com/questions/13152/how-to-perform-orthogonal-regression-total-least-squares-via-pca also can read about regression dilution on wiki: https://en.wikipedia.org/wiki/Regression_dilution – Bryan Shalloway Jan 22 '21 at 21:05

1 Answers1

12

As hinted at in this answer you should be able to use approx() for your task. E.g. like this:

xval <- approx(x = fit$fitted.values, y = x, xout = 30)$y

points(xval, 30, col = "blue", lwd = 5)

Gives you:

enter image description here

Community
  • 1
  • 1
Felix
  • 1,611
  • 13
  • 22
  • 3
    Just to add, `spline` function is also available for a non-linear interpolation, as an alternative to `approx` function which is linear. – cylim Apr 10 '17 at 12:48