Diff() 在 nlsLM 包中不兼容?

Diff() incompatable in nlsLM package?

问题:先谢谢了! nlsLM 不能与 diff 一起使用吗?我只是想做 g*(p[i]-p[i-1])/(x[i]-x[i-1])并用nlsLM求拟合参数g的值可以拟合y 我使用 diff 没有 nlsLM 如下,

`g*diff(df$p)/diff(df$x)`

而且效果很好:

`[1] 0.4 3.0 3.0`

但是,当我将它与 nlsLM 一起使用时,它不起作用,我得到以下信息:

`Error in qr(.swts * attr(rhs, "gradient")) : 
  dims [product 3] do not match the length of object [4]
In addition: Warning messages:
1: In lhs - rhs :
  longer object length is not a multiple of shorter object length
2: In lhs - rhs :
  longer object length is not a multiple of shorter object length
3: In lhs - rhs :
  longer object length is not a multiple of shorter object length
4: In lhs - rhs :
  longer object length is not a multiple of shorter object length
5: In lhs - rhs :
  longer object length is not a multiple of shorter object length
6: In lhs - rhs :
  longer object length is not a multiple of shorter object length
7: In lhs - rhs :
  longer object length is not a multiple of shorter object length
8: In .swts * attr(rhs, "gradient") :
  longer object length is not a multiple of shorter object length`

代码:

# Packages:
library(tidyverse)
library(minpack.lm) 

# undoing tidyverse's masking effects( Courtesy of user Kat)
filter <- dyplr::filter 
lag <- dplyr::lag 

#df
df<-data.frame(x=c(9,14,15,17),p=c(11,13,16,22),y=c(16,19,25,35))

#object

g<-5

#nlsLM run: finding fitting parameter g's value

summary(nlsLM(formula=y~g*diff(p)/diff(x),
              data=df,trace=F,
              start=list(g=5),control=nls.lm.control(maxiter=1000)))

我们假设您对以下最小二乘模型感兴趣,其中 n 是 nrow(df)

y[i] ~ g * (p[i] - p[i-1]) / (x[i] - x[i-1]) for i = 2, ..., n

1) nlsLM 现在 diff(x)x 短一个因为对于第一个元素没有要减去的先前元素所以使用这个

y1 <- df$y[-1]
nlsLM(y1 ~ g * diff(p) / diff(x), df, start = list(g = 5))

给予:

Nonlinear regression model
  model: y1 ~ g * diff(p)/diff(x)
   data: df
    g 
10.33 
 residual sum-of-squares: 273

Number of iterations to convergence: 2 
Achieved convergence tolerance: 1.49e-08

2) nls 注意我们可以使用 nls

y1 <- df$y[-1]
nls(y1 ~ g * diff(p) / diff(x), df, start = list(g = 5))

3) lm 因为这在单个参数 g 中是线性的,我们也可以使用 lm

lm(y[-1] ~ I(diff(p) / diff(x)) + 0, df)

4) dyn dyn 包可以使用 lm 和其他某些使用 model.frame 使用 zoo 或 ts 的回归函数自动处理此问题。

library(dyn)
dyn$lm(y ~ I(diff(p) / diff(x)) + 0, zoo(df))

已添加

关于评论中的问题,该评论中的错误是由对齐错误引起的。试试这个对我来说收敛于 6 次迭代。

y1 <- df$y[-1]
p1 <- df$p[-1]
pL <- df$p[-nrow(df)]

fo <- y1 ~ g*((   (1/ (1 + exp((g)*((1/p1)-(1/(p1)))))) -
    (1/ (1 + exp((g)*((1/pL)-(1/(p1)))))) ) /(p1-pL))
nls(fo, start = list(g = 5))