简体   繁体   English

R预测()仅返回nls()模型的拟合值

[英]R predict() returns only fitted values for nls() model

First of all, I would like to mention I am just a beginner in R. I have encountered a problem when trying to predict data from a model generated by nls(). 首先,我想提到我只是R语言的初学者。尝试从nls()生成的模型预测数据时遇到了一个问题。 I fitted the exponential decay function into my data and everything seems to be fine, eg I got a decent regression line. 我将指数衰减函数拟合到我的数据中,一切似乎都很好,例如,我得到了不错的回归线。 However, when I use predict() on a new data set, it returns only fitted values. 但是,当我在新数据集上使用predict()时,它仅返回拟合值。

My code is: 我的代码是:

df = data.frame(Time = c(0,5,15,30), Value = c(1, 0.38484677,0.18679383, 0.06732328))

model <- nls(Value~a*exp(-b*Time), start=list(a=1, b=0.15), data = df)

plot(Value~Time, data = df)

lines(df$Time, predict(model))

生成图

newtime <- data.frame(Time = seq(1,20, by = 1))

pr = predict(model, newdata = newtime$Time)

pr
[1] 0.979457389 0.450112312 0.095058637 0.009225664

Could someone explain me please, what I am doing wrong? 有人可以解释一下,我做错了吗? I know there are here some answers to that problem, but none helped me. 我知道这里有一些解决该问题的方法,但是没有一个帮助我。

Thank you in advance for your help! 预先感谢您的帮助!

The newdata parameter should be a data.frame with the same names as your input data. newdata参数应该是与输入数据名称相同的data.frame。 When you use newdata = newtime$Time you are actually passing in newtime$Time which is not a data.frame anymore since it 'dropped' down to a vector. 当您使用newdata = newtime$Time您实际上传递的是newtime$Time ,它不再是data.frame,因为它被“下拉”为向量。 You can just pass in newtime like so 你可以像这样传递新时间

pr = predict(model, newdata = newtime)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM