Protect Function Evaluations

Description

Ensures non-failure and possibly finite-ness of a function evaluation.

Usage

1
2
protect(f, fail.value.default=NULL)
invert(f)

Arguments

f

A function.

fail.value.default

Value that will be used as on failure of f, if not overridden. The default here (NULL) will allow failure.

Details

protect returns a function with arguments

1
2
    g(..., fail.value=fail.value.default, finite=NULL)
  

The ... arguments are all passed through to the underlying function f, fail.value contains the value to return in the event of a failure (e.g., an error occuring). If finite is TRUE, then fail.value is also returned where the value is NA, NaN or infinite.

Some functions, such as optim with method L-BFGS-B (and therefore find.mle), require that every value is finite. Optimisation with these functions also requires that the target functions to not generate errors. protect catches these issues, returning the value of fail.value instead.

No check is made that f returns a single value, but it should.

Author(s)

Richard G. FitzJohn

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
f <- function(x) log(x)
g <- protect(f)
f(0) # -Inf
g(0, fail.value=-999) # -999

f <- function(x) {
  if ( x < 1 )
    stop("dummmy error")
  x
}
g <- protect(f)
## Not run: 
f(0) # error

## End(Not run)
g(0, fail.value=-999) # -999

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.