如何解决如何计算 R 中自定义函数的非线性最小二乘法?
我正在尝试使用 this example 之后的自定义函数运行非线性最小二乘法 数据集有 x、预测变量 y 和组 (a/b)。我以前只使用过 MLL 代码。我很难围绕如何将函数调用到 nls 以及如何进行后续 nls 拟合。我附上了我尝试过的代码以及适用的错误。
# generate data
set.seed(2)
x <- rep(sample(1:100,9),12)
set.seed(15)
r <- rnorm(x,mean = 0,sd = 200*x^-0.8)
y <- c(200,300) * exp(c(-0.08,-0.05)*x) + c(120,100) + r
df <- data.frame(x = x,y = y,group = rep(letters[1:2],length.out = length(x)))
ga <- function(aa,K,Ka,q,c){
p <- x / K
lnqp <- if (q == 0) log(p) else (p^q - 1) / q
y <- (aa * (p * K / Ka - 1) - 1) * lnqp + c
}
m <- nls(y ~ ga(aa,c))
Error in q == 0 :
comparison (1) is possible only for atomic and list types
In addition: Warning message:
In nls(y ~ ga(aa,c)) :
No starting values specified for some parameters.
Initializing ‘aa’,‘K’,‘Ka’ to '1.'.
Consider specifying 'start' or using a selfStart model
summary(m)
plot(m)
#ERROR: Error in q == 0 :
comparison (1) is possible only for atomic and list types
# fit generalised nonlinear least squares
require(nlme)
mgnls <- gnls(y ~ ga(aa,c),start = list(aa = c(356.6851,356.6851),K = c(-exp(-2.9356),-exp(-2.9356)),Ka = c(-exp(-2.9356),q = c(-exp(-2.9356),c = c(108.9860,108.9860)),params = list(aa ~ group,K ~ group,Ka ~ group,q ~ group,c ~ group),weights = varExp(),data = df)
plot(mgnls) # more homogenous
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。