首页 > 解决方案 > 在 lapply 函数中使用 nls 时出现错误消息

问题描述

我有一个关于 nls 功能的问题。我正在尝试为每个物种(我总共有 13 个物种)绘制具有 von Bertalanffy 生长(长度和年龄)的图。

首先我制作了一个数据框列表,每个数据框都包含特定物种的数据

dfss <- split(df, list(df$Species.Name),drop=TRUE,sep="/")

然后我有一个函数来计算模型


VGBF<-function(xi){
  
 #VGBF.calc
    agesum<-xi %>% group_by(Species.Name) %>% summarise(minage=min(age),maxage=max(age))
    measures<-as.data.frame(cbind(Length_1=xi$Length_1,age=xi$age))
   vb<-vbFuns(param="Typical")
   f.starts<-vbStarts(Length_1~age,data=measures)
   f.fit<-  nls(Length_1~vb(age,Linf,K,t0),data=measures,start=f.starts,nls.control(maxiter = 1000))
  #  coef(f.fit)
  # f.boot1<- Boot(f.fit)
  # confint(f.boot1)
  # predict(f.fit,data.frame(age=unique(xi$minimum.age):unique(xi$maximum.age)))
 

  predict2<- function(x) {predict(x,data.frame(age=ages))}
  ages<-unique(xi$minimum.age):unique(xi$maximum.age)
  predict2(f.fit)
  
  ages<-seq(unique(xi$minimum.age)-2,unique(xi$maximum.age)+2,by=0.2)
  f.boot2<-Boot(f.fit,f=predict2)
  preds1<-data.frame(ages,
                     predict(f.fit,data.frame(age=ages)),
                     confint(f.boot2))
  names(preds1)<-c("age","fit","LCI","UCI")
  preds2<-filter(preds1,age>=agesum$minage,age<=agesum$maxage)}

然后我将该函数应用于包含每个物种信息的列表

lapply(dfss,VGBF)

我有以下错误消息

Error in nls(Length_1 ~ cvb(age, Linf, K, t0), data = measures, astart=f.starts, : 
 step factor 0.000488281 reduced below 'minFactor' of 0.000976562

该脚本在没有嵌套在 lapply 函数中时运行良好(使用针对特定物种过滤的原始数据集作为用于 VGBF 函数内容的数据框)。

当我使用 for 循环而不是 lapply 函数时,它似乎也不起作用。

所以,我的问题是如何克服这个问题。

我希望我的问题足够清楚。

先感谢您

标签: rlapplynls

解决方案


推荐阅读