1

我正在尝试使用将"nlmrt对象转换为"nls"对象nls2。但是,只有在调用中明确写入参数的名称时,我才能做到这一点。我不能以编程方式定义参数名称吗?请参阅可重现的示例:

library(nlmrt)

scale_vector <- function(vector, ranges_in, ranges_out){
    t <- (vector - ranges_in[1, ])/(ranges_in[2, ]-ranges_in[1, ])
    vector <- (1-t) * ranges_out[1, ] + t * ranges_out[2, ] 
}

shobbs.res  <-  function(x) {
    # UNSCALED Hobbs weeds problen -- coefficients are rescaled internally using
    # scale_vector

    ranges_in  <- rbind(c(0, 0, 0), c(100, 10, 0.1))
    ranges_out <- rbind(c(0, 0, 0), c(1, 1, 1)) 
    x <- scale_vector(x, ranges_in, ranges_out)

    tt <- 1:12
    res <- 100*x[1]/(1+10*x[2]*exp(-0.1*x[3]*tt)) - y }


y  <-  c(5.308, 7.24, 9.638, 12.866, 17.069, 23.192, 31.443, 
         38.558, 50.156, 62.948, 75.995, 91.972)
st  <-  c(b1=100, b2=10, b3=0.1)

ans1n <- nlfb(st, shobbs.res)
print(coef(ans1n))

这有效:

library(nls2)
ans_nls2 <- nls2(y ~ shobbs.res(c(b1, b2, b3)) + y, start = coef(ans1n), alg = "brute")

但是,这迫使我在调用中对参数名称进行硬编码nls2。由于与我的实际代码相关的原因,我希望能够做类似的事情

ans_nls2 <- nls2(y ~ shobbs.res(names(st)) + y, start = coef(ans1n), alg = "brute")

但这会返回一个错误:

    Error in vector - ranges_in[1, ] : 
  non-numeric argument to binary operator 

是否可以解决这个问题,而不必在调用中明确地硬编码参数的名称nls2

4

1 回答 1

1

nls2将接受一个字符串作为公式:

co <- coef(ans1n)
fo_str <- sprintf("y ~ shobbs.res(c(%s)) + y", toString(names(co)))

nls2(fo_str, start = co, alg = "brute")

给予:

Nonlinear regression model
  model: y ~ shobbs.res(c(b1, b2, b3)) + y
   data: NULL
      b1       b2       b3 
196.1863  49.0916   0.3136 
 residual sum-of-squares: 2.587

Number of iterations to convergence: 3 
Achieved convergence tolerance: NA
于 2017-04-10T11:01:55.437 回答