Adam SO
Adam SO

Reputation: 9991

How to force a function to pass a certain object (e.g. value) instead of failing and passing an error message

Is there a way to force the function to pass a value (e.g. 0) instead of failing and passing an error message to the screen?
The reason for asking is that I try to include an lme function(nlme) in an aggregate (stats) of a table but the lme function sends an error message in certain cases and the aggregate call fails. example of the error message and the situation that cause it.

ID= c("3", "15", "24", "25", "26", "28", "29", "30")
    value= c(0, 0, 0, 0, 0, 0, 0, 0)
    fit = lme(value ~ 1, random = ~ 1 | ID)
    Error in chol.default((value + t(value))/2) : 
      the leading minor of order 1 is not positive definite

Thanks!

Upvotes: 0

Views: 1028

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226077

?try and/or ?tryCatch are your friends (they may even be documented on the same page).

I usually use an idiom like

ncoefs <- 5
fit <- lme(...)
if (inherits(fit,"try-error")) rep(NA,ncoefs) else fixef(fit)

(inherits() is more general than if class()==... because class() can return a vector of characters with length > 1 ...)

Upvotes: 4

Related Questions