使用R的tryCatch

时间:2016-11-02 17:06:13

标签: r try-catch

尝试使用R的{​​{1}}将对数逻辑曲线拟合到剂量反应数据中:

tryCatch

使用df <- data.frame(dose=c(10,0.62,2.5,0.16,0.039,0.0024,0.0098,0.00061,10,0.62,2.5,0.16,0.039,0.0024,0.0098,0.00061,10,0.62,2.5,0.16,0.039,0.0024,0.0098,0.00061), viability=c(22,79,100,61,100,87,75,51,6.5,37,100,100,90,100,42,41,5,100,13,100,91,100,95,100), stringsAsFactors = F) 的{​​{1}}函数使用此代码:

drc

我明白了:

drm

然而,当我尝试没有library(drc) fit <- tryCatch( { drm(viability~dose,data=df,fct=LL.4(names=c("slope","low","high","ED50"))) }, error=function(cond){ return(NA) }, warning=function(cond){ return(NA) }, finally={ } ) 时,没有问题:

> fit
[1] NA

我没有正确使用tryCatch吗?

1 个答案:

答案 0 :(得分:2)

您正在使用tryCatch。你的代码正在发出警告。我修改了您的代码以返回错误或警告消息:

fit <- tryCatch(
  {
    drm(viability~dose,data=df,fct=LL.4(names=c("slope","low","high","ED50")))
  },
  error=function(cond){
    return(cond)
  },
  warning=function(cond){
    return(cond)
  },
  finally={  
  }
)

现在正在运行fit会显示drm正在发出警告:

> fit
<simpleWarning in log(dose/parmMat[, 4]): NaNs produced>