简体   繁体   English

如何拟合具有混合效果的 nls 模型

[英]How to fit a nls model with mixed effects

I want to fit a linear-plateau model with random effects.我想拟合具有随机效应的线性平台模型。 I found a way to fit the function with nls() , but I don't know how to include random effects.我找到了一种用nls()拟合函数的方法,但我不知道如何包含随机效应。 Here is what i have so far:这是我到目前为止所拥有的:

#create data
x=c(1:6,1:6)
y=c(10,21,27,35,33,35,9,20,28,32,30,31)
z=c("A","A","A","A","A","A","B","B","B","B","B","B")
df<-data.frame(x,y,z)

#create linear-plateau function
lp=function(x, a, b, c){
  ifelse(x > c, a + b * c, a + b * x)
  }

#fit the model without random effects
p10=nls(y ~ lp(x, a, b, c), data = df, start = list(a = 0, b = 15, c = 4))


plot(y~x)
lines(x=c(0, coef(p10)["c"],max(df$x)), 
      y=c(coef(p10)["a"],
          (coef(p10)["a"] + coef(p10)["b"] * coef(p10)["c"]),
          (coef(p10)["a"] + coef(p10)["b"] * coef(p10)["c"])),lty=2)

What I want to do is to include z as a random effect, since all data collected from the same z level are not independent.我想要做的是将z作为随机效应包括在内,因为从同一z级别收集的所有数据都不是独立的。 I know how to model mixed effects with nlmer function from lme4 package, but I don't know how to fit the linear-plateau model with it.我知道如何混合效应与模型nlmer从功能lme4包,但我不知道如何与它适合线性台阶模型。

You can do this with the nlme package, but the data you've given us aren't going to be sufficient to succeed in fitting a random-effects model.您可以使用nlme包执行此操作,但是您提供给我们的数据不足以成功拟合随机效应模型。

Start by fitting a gnls() (generalized non-lin least squares) model, which allows for fixed-effect differences among groups:首先拟合gnls() (广义非线性最小二乘法)模型,该模型允许组间的固定效应差异:

library(nlme)
p20 = gnls(y ~ lp(x, a, b, c),
           params= list(a+b~z, c~1),
           data = df,
           start = list(a = c(0,0), b=c(15,15), c=4))

(I initially tried params = list(a+b+c~z) , with appropriate changes to start , but the fit didn't succeed. It might be possible to tweak control parameters to make that model work ...) (我最初尝试params = list(a+b+c~z) ,对start进行适当的更改,但拟合没有成功。可能可以调整控制参数以使该模型工作......)

Now as a random effects model.现在作为随机效应模型。 This doesn't succeed - you would almost definitely need to have more than two groups - but it should give you the idea.这不会成功 - 你几乎肯定需要有两个以上的组 - 但它应该给你这个想法。

p30 = nlme(y ~ lp(x, a, b, c),
           random = a+b~1|z,
           fixed = a+b+c ~ 1,
           data = df,
           start = c(a=0, b=15, c=4)
           )

Doing this with nlmer is a little fussier as you have to define a function that returns the gradients as well as the value of the objective function.使用nlmer执行此nlmer有点nlmer因为您必须定义一个函数来返回梯度以及目标函数的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM