使用拟合模型从 Y 值预测 X 值

Predict X value from Y value with a fitted model

我需要使用拟合模型预测新 y 值的相应 x 值。

从新的 x 值预测 y 值的通常情况是使用 predict 函数很简单,但我不知道如何做相反的事情。

对于有多个x解的情况,我希望得到x值范围内的所有解,即1-10。并且新的 y 将始终在用于拟合模型的 y 值的范围内。

请参阅下面的示例代码,我需要在其中找到新的 x 值 (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') 

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

编辑 1:反向拟合

拟合反向关系不会给出相同的模型,因为我们得到了不同的 model/fitted 行。

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) 

中所暗示,您应该能够使用 approx() 完成您的任务。例如。像这样:

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

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

给你: