微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

R 非线性最小二乘 (nls) 函数:使用索引向量作为输入?

如何解决R 非线性最小二乘 (nls) 函数:使用索引向量作为输入?

我正在尝试使用索引向量作为输入在 R 中运行 nls 函数,但是出现错误

> a=c(1,2,3,4,5,6,7,8,9,10)
> b=c(6,11,14,18,23,30,38,50) #make some example data
>
> nls(b[1:6]~s+k*2^(a[1:6]/d),start=list(s=2,k=3,d=2.5)) #try running nls on first 6 elements of a and b
Error in parse(text = x,keep.source = FALSE) :
  <text>:2:0: unexpected end of input
1: ~
   ^

可以在完整向量上运行它:

> nls(b~s+k*2^(a/d),d=2.5))
Nonlinear regression model
  model: b ~ s + k * 2^(a/d)
   data: parent.frame()
    s     k     d
1.710 3.171 2.548
 residual sum-of-squares: 0.3766

Number of iterations to convergence: 3
Achieved convergence tolerance: 1.2e-07

我相当确定索引向量与完整向量具有相同的变量类型:

> a
 [1]  1  2  3  4  5  6  7  8  9 10
> typeof(a)
[1] "double"
> class(a)
[1] "numeric"

> a[1:6]
[1] 1 2 3 4 5 6
> typeof(a[1:6])
[1] "double"
> class(a[1:6])
[1] "numeric"

如果我将索引向量保存在新变量中,我可以运行 nls

> a_part=a[1:6]
> b_part=b[1:6]
> nls(b_part~s+k*2^(a_part/d),d=2.5))
Nonlinear regression model
  model: b_part ~ s + k * 2^(a_part/d)
   data: parent.frame()
    s     k     d
2.297 2.720 2.373
 residual sum-of-squares: 0.06569

Number of iterations to convergence: 3
Achieved convergence tolerance: 1.274e-07

此外,lm 接受完整和索引向量:

> lm(b~a)

Call:
lm(formula = b ~ a)

Coefficients:
(Intercept)            a
     -4.667        4.594

> lm(b[1:6]~a[1:6])

Call:
lm(formula = b[1:6] ~ a[1:6])

Coefficients:
(Intercept)       a[1:6]
      2.533        2.371

有没有办法在索引向量上运行 nls 而不将它们保存在新变量中?

解决方法

使用 subset 。 (也可以使用 weights 参数为前 6 个观察值中的每一个赋予 1 的权重,其余的为 0。)

此外,您可能希望使用 plinear 算法来避免为线性输入的两个参数提供起始值。在这种情况下,在 RHS 上提供一个矩阵,其列名称为 s 和 k,这样它的第一列乘以 s,第二列乘以 k

nls(b ~ cbind(s = 1,k = 2^(a/d)),subset = 1:6,start = list(d = 2.5),algorithm = "plinear")

给予:

Nonlinear regression model
  model: b ~ cbind(s = 1,k = 2^(a/d))
   data: parent.frame()
     d .lin.s .lin.k 
 2.373  2.297  2.720 
 residual sum-of-squares: 0.06569

Number of iterations to convergence: 3 
Achieved convergence tolerance: 7.186e-08

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。