问题描述
我需要使用拟合模型预测新的y
值对应的x
值.
I need to predict the corresponding x
value of a new y
value using a fitted model.
通过使用predict
函数从新的x
值预测y
值的通常情况很简单,但是我不知道该怎么做.
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.
对于具有多个x
解决方案的情况,我希望获得x
值范围内的所有解决方案,即1-10
.并且新的y
将始终在用于拟合模型的y
值的范围内.
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.
请参见下面的示例代码,我需要在其中找到新的x值(new_x
).
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')
new_y = 30
new_x = predict(fit, data.frame(y=new_y)) #This line does not work as intended.
反拟合
由于我们得到了不同的模型/拟合线,因此拟合反向关系不会得到相同的模型.
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)
推荐答案
如,您应该可以使用approx()
来完成任务.例如.像这样:
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)
给你:
这篇关于使用拟合模型从Y值预测X值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!