【发布时间】:2019-03-13 14:43:28
【问题描述】:
我有一个数据集,我想按组应用非线性最小二乘。这是我之前的问题的延续: NLS Function - Number of Iterations Exceeds max
数据集如下所示:
df
x y GRP
0 0 1
426 9.28 1
853 18.5 1
1279 27.8 1
1705 37.0 1
2131 46.2 1
0 0 2
450 7.28 2
800 16.5 2
1300 30.0 2
2000 40.0 2
2200 48.0 2
如果我要对一组进行此操作,它会是这样的:
df1<-filter(df, GRP==1)
a.start <- max(df1$y)
b.start <- 1e-06
control1 <- nls.control(maxiter= 10000,tol=1e-02, warnOnly=TRUE)
nl.reg <- nls(y ~ a * (1-exp(-b * x)),data=df1,start=
list(a=a.start,b=b.start),
control= control1)
coef(nl.reg)[1]
coef(nl.reg)[2]
> coef(nl.reg)[1]
a
5599.075
> coef(nl.reg)[2]
b
3.891744e-06
然后我会为 GRP2 做同样的事情。我希望我的最终输出如下所示:
x y GRP a b
0 0 1 5599.075 3.891744e-06
426 9.28 1 5599.075 3.891744e-06
853 18.5 1 5599.075 3.891744e-06
1279 27.8 1 5599.075 3.891744e-06
1705 37.0 1 5599.075 3.891744e-06
2131 46.2 1 5599.075 3.891744e-06
0 0 2 New Value for a GRP2 New Value for b GRP2
450 7.28 2 New Value for a GRP2 New Value for b GRP2
800 16.5 2 New Value for a GRP2 New Value for b GRP2
1300 30.0 2 New Value for a GRP2 New Value for b GRP2
2000 40.0 2 New Value for a GRP2 New Value for b GRP2
2200 48.0 2 New Value for a GRP2 New Value for b GRP2
理想情况下,我认为 dplyr 是最好的方法,但我不知道该怎么做。这就是我认为它可能的样子:
control1 <- nls.control(maxiter= 10000,tol=1e-02, warnOnly=TRUE)
b.start <- 1e-06
df %>%
group_by(GRP) %>%
do(nlsfit = nls( form = y ~ a * (1-exp(-b * x)), data=.,
start= list( a=max(.$y), b=b.start),
control= control1) ) %>%
list(a = coef(nlsfit)[1], b = coef(nlsfit)[2])
错误:
in nlsModel(formula, mf, start, wts) :
singular gradient matrix at initial parameter estimates
虽然不确定如何执行此操作,但任何帮助都会很棒。谢谢!
【问题讨论】:
-
你的代码有错误
df1<-filter(df, GRP=1)应该是df1<-filter(df, GRP==1) -
感谢您了解这一点,我实际上并没有运行该部分。只是为了演示目的而展示它。
-
@42 这个问题有意义吗?
-
确实如此。答案需要整洁吗?我发现这种环境在很多时候都很难理解。
-
不,它只需要动态的,不管有多少组。我的实际数据集有 5000 个组,使总数据集接近 1MM 行。根据我的研究,Dplyr 通常是处理速度最快的。
标签: r dplyr regression nls