有条件的nls适合dplyr +扫帚

时间:2015-08-19 23:24:39

标签: r if-statement dplyr nls

我正在使用dplyr和扫帚组合,并尝试根据数据组内部的条件拟合回归模型。最后,我想提取每组的回归系数。

到目前为止,我为所有组获得了相同的拟合结果(每组用字母a:f分隔)。这是主要问题。

library(dplyr)
library(minpack.lm)
library(broom)

direc <- rep(rep(c("North","South"),each=20),times=6)
V <- rep(c(seq(2,40,length.out=20),seq(-2,-40,length.out=20)),times=1)
DQ0 = c(replicate(2, sort(runif(20,0.001,1))))
DQ1 = c(replicate(2, sort(runif(20,0.001,1))))
DQ2 = c(replicate(2, sort(runif(20,0.001,1))))
DQ3 = c(replicate(2, sort(runif(20,0.001,1))))
No  =  c(replicate(1,rep(letters[1:6],each=40)))

df <-   data.frame(direc,V,DQ0,DQ1,DQ2,DQ3,No)
适合条件可描述如下; 如果direc=NorthV<J1exp((-t_pw)/f0*exp(-del1*(1-V/J1)^2))direc=South符合等式V>J2,那么V<J1 用同样的方程拟合。在这两种情况下,如果V>J2&amp;对于每个案例,1都不满意返回nls

更新 我发现条件nls_fit=nlsLM(DQ0~ifelse(df$direc=="North"&V<J1, exp((-t_pw)/f0*exp(-del1*(1-V/J1)^2)),1)*ifelse(df$direc=="South"&V>J2, exp((-t_pw)/f0*exp(-del2*(1-V/J2)^2)),1) ,data=df,start=c(del1=1,J1=15,del2=1,J2=-15),trace=T) 可以通过此链接中的建议conditional-formula-for-nls

Nonlinear regression model
  model: DQ0 ~ ifelse(df$direc == "North" & V < J1, exp((-t_pw)/f0 * exp(-del1 *     (1 - V/J1)^2)), 1) * ifelse(df$direc == "South" & V > J2,     exp((-t_pw)/f0 * exp(-del2 * (1 - V/J2)^2)), 1)
   data: df
   del1      J1    del2      J2 
  1.133  23.541   1.079 -20.528 
 residual sum-of-squares: 16.93

Number of iterations to convergence: 4 
Achieved convergence tolerance: 1.49e-08

nls_fit

DQ0:DQ3

另一方面,当我尝试适应其他列,如DQ1,DQ2和DQ3;

我试过了     nls_fit = nlsLM(DF [,3:6]〜ifelse(.....

nls.lm中的错误(par = start,fn = FCT,jac = jac,control = control,lower = lower,:   fn函数的评估返回非敏感值!

现在问题归结为多列拟合。如何安装多列DQ0?我检查了how to succinctly write a formula with many variables from a data frame?,但找不到我的数据框中使用的解决方案。

此外,当我在其组内部适合a:f列时 从输出中可以看出,为所有组df_new<- df%>% group_by(No)%>% do(data.frame(model=tidy()))>% ungroup

生成相同的Del和J参数
Source: local data frame [24 x 6]

   No model.term model.estimate model.std.error model.statistic model.p.value
1   a       del1       1.132546        9024.255    1.255002e-04     0.9999000
2   a         J1      23.540764      984311.373    2.391597e-05     0.9999809
3   a       del2       1.079182       27177.895    3.970809e-05     0.9999684
4   a         J2     -20.527520     2362268.839   -8.689748e-06     0.9999931
5   b       del1       1.132546        9024.255    1.255002e-04     0.9999000
6   b         J1      23.540764      984311.373    2.391597e-05     0.9999809
7   b       del2       1.079182       27177.895    3.970809e-05     0.9999684
8   b         J2     -20.527520     2362268.839   -8.689748e-06     0.9999931
9   c       del1       1.132546        9024.255    1.255002e-04     0.9999000
10  c         J1      23.540764      984311.373    2.391597e-05     0.9999809
.. ..        ...            ...             ...             ...           ...
  

df_new

{{1}}

0 个答案:

没有答案