R语言,非线性模型公式预测

use*_*394 2 r nls predict

我用一组数据 (x, y) 拟合指数公式。然后我想根据公式计算 y 值,其中 x 值超出实际数据集。它不起作用,总是打印实际 x 值的 y 值。这是代码。我做错了什么?我的 R 语言任务的解决方案是什么:

data <- data.frame(x=seq(1,69), y=othertable[1:69, 2])
nlsxypw <- nls(data$y ~ a*data$x^b, col2_60, start=list(a=2200000, b=0))
predict(nlsxypw)
#here I want to calculate the y values for x = 70-80
xnew <- seq(70, 80, 1)
predict(nlsxypw, xnew)

#it doesn't print these values, still the actual values for x=1~69.
Run Code Online (Sandbox Code Playgroud)

nru*_*ell 5

这是一种奇怪的功能predict.nls(可能predict还有其他方法?),但是您必须提供与模型定义相同的名称的新数据:

set.seed(123)
Data <- data.frame(
  x = 1:69, 
  y = ((1:69)**2)+rnorm(69,0,5))
nlsxypw <- nls(y ~ a*(x^b),
               data=Data,
               start=list(a=2.5, b=1))
##
xnew <- 70:80
## note how newdata is specified
y.pred <- predict(nlsxypw, newdata=list(x=xnew))
> y.pred
 [1] 4900.355 5041.359 5184.364 5329.368 5476.373 5625.377 5776.381 5929.386 6084.390 6241.393 6400.397
##
with(
  Data,
  plot(x,y,pch=20,
       xlim=c(0,90),
       ylim=c(0,6700)))

lines(fitted(nlsxypw),col="red")
points(
  x=xnew,
  y=y.pred,
  pch=20,
  col="blue")
##
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 它不仅仅是“predict.nls”,它几乎是所有“predict()”函数。大多数人期望 data.frame (或 list())并且变量的名称必须完全匹配。这就是为什么像 nrussell 那样使用 `data=` 参数总是一个好主意,而不是在公式中使用“$”。当模型只有一个独立协变量时,不存在“特殊情况”。 (2认同)