[R] tryCatch in a package

Sebastian P. Luque spluque at gmail.com
Thu Mar 8 03:35:25 CET 2012


Suppose we have a general function that returns a logical indicating
which values in 'x' are found in 'l', throwing an error if none are
found and a warning if only some are found:

"checkFun" <- function(l, x)
    xinl <- x %in% l
    if (! any(xinl)) stop("none of the x values found in l")
    if (any(! xinl))
        warning("x ", x[! xinl], " do(es) not exist")

This function would be used in several other functions that need to stop
and throw the error message or give the warning and use the logical
value, as here:

"getListElement" <- function(k, y) {
        ok <- checkFun(names(k), y)
        dm <- k[y[ok]]
        if (length(y) == 1L) dm[[1]] else dm # just to simplify if only 1

K <- list(A=1, B=2, C=3)
Y <- LETTERS[1:5]
getListElement(K, Y)

Is this good practice in a package, or should the functionality of
checkFun() be implemented inside tryCatch via the different handlers?



More information about the R-help mailing list