dan
dan

Reputation: 6314

Using R's tryCatch

Trying to use R's tryCatch on fitting a log-logistic curve to a dose-response data:

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)

with drc's drm function using this code:

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={  
  }
)

I get:

> fit
[1] NA

However, when I try without tryCatch there's no problem:

> drm(viability~dose,data=df,fct=LL.4(names=c("slope","low","high","ED50")))

A 'drc' model.

Call:
drm(formula = viability ~ dose, data = df, fct = LL.4(names = c("slope",     "low", "high", "ED50")))

Coefficients:
slope:(Intercept)    low:(Intercept)   high:(Intercept)   ED50:(Intercept)  
            1.498           -163.577             81.031             18.481  

Am I not using tryCatch correctly?

Upvotes: 0

Views: 278

Answers (1)

jkr
jkr

Reputation: 19310

You are using tryCatch correctly. Your code is throwing a warning. I modified your code to return the error or warning message:

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={  
  }
)

And now running fit reveals that drm is throwing a warning:

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

Upvotes: 2

Related Questions