nls:循环并中断确定的迭代次数

时间:2019-04-21 22:09:40

标签: r loops nls

我喜欢对顺序操作进行以下两种操作:

1)调整了子集中的两个nls模型;和 2)仅将迭代次数= 1循环到模型。

第一步,我要做:

#Packages
library(minpack.lm)

# Data set - Diameter in function of Feature and Age
Feature<-sort(rep(c("A","B"),22))
Age<-c(60,72,88,96,27,
36,48,60,72,88,96,27,36,48,60,72,
88,96,27,36,48,60,27,27,36,48,60,
72,88,96,27,36,48,60,72,88,96,27,
36,48,60,72,88,96)
Diameter<-c(13.9,16.2,
19.1,19.3,4.7,6.7,9.6,11.2,13.1,15.3,
15.4,5.4,7,9.9,11.7,13.4,16.1,16.2,
5.9,8.3,12.3,14.5,2.3,5.2,6.2,8.6,9.3,
11.3,15.1,15.5,5,7,7.9,8.4,10.5,14,14,
4.1,4.9,6,6.7,7.7,8,8.2)
d<-dados <- data.frame(Feature,Age,Diameter)
str(d)

#Create a nls model (Levenberg-Marquardt  algoritm) for each Feature (A abd B)
e1<- Diameter ~ a1 * Age^a2 
Fecture_vec<-unique(d$Feature)
mod_ND <- list() #List for save each model
for(i in 1:length(Fecture_vec)){
     d2 <- subset(d, d$Feature == Fecture_vec[i])
     mod_ND[[i]] <-  nlsLM(e1, data = d2,
     start = list(a1 = 0.1, a2 = 10),
     control = nls.control(maxiter = 1000))
print(summary(mod_ND[[i]]))
}
#

到目前为止,到目前为止还不错,但是如果我尝试使用999模拟进行循环并使用coef(mod_ND[[i]])[1]coef(mod_ND[[i]])[2]回收起始值,并在迭代次数为1时停止运行:

e1<- Diameter ~ a1 * Age^a2 
Fecture_vec<-unique(d$Feature)
mod_ND <- list() #List for save each model
for(i in 1:length(Fecture_vec)){
     d2 <- subset(d, d$Feature == Fecture_vec[i])
     mod_ND[[i]] <-  nlsLM(e1, data = d2,
     start = list(a1 = 0.1, a2 = 10),
     control = nls.control(maxiter = 1000))
Xs<-data.frame()
for(z in 1:999){
     d2 <- subset(d, d$Feature == Fecture_vec[i])
     mod_ND[[z]] <-  nlsLM(e1, data = d2,
     start = list(a1 = coef(mod_ND[[i]])[1], a2 = mod_ND[[i]])[2]),
     control = nls.control(maxiter = 1000))
   if (mod_ND[[z,c(finIter")]] <= 1){ break } ## Stop when iteractions =1
print(summary(mod_ND[[z]]))
}
}
#

不起作用!!有什么想法吗?

1 个答案:

答案 0 :(得分:0)

#Packages
library(minpack.lm)
library(dplyr)

m<-function(d, a=0.01,b=10){

   mod<- nlsLM(Diameter ~ a1 * Age^a2,start = list(a1 = a, a2 = b),control = nls.control(maxiter = 1000), data = d)
   par1<- summary(mod)$coefficients[[1]]
    par2 <- summary(mod)$coefficients[[2]]
   print(summary(mod))

   if(mod$convInfo[["finIter"]]>1){    
       m(d,par1,par2)      
  }else{
       print(" --------Feature B-----------")
   }         
    }
list_models <- dlply(d,.(Feature),m)   
list_models