Personal code snippets of @tmasjc

Site powered by Hugo + Blogdown

Image by Mads Schmidt Rasmussen from unsplash.com

Minimal Bootstrap Theme by Zachary Betz

Safe Function Using Base R

May 21, 2021

f <- function(i){
    if (!is.numeric(i)) stop("Not a number!")
    if (i > 10) warning("Number is bigger than 10.")
    return(i)
}


custom_f <- function(x) {
    
    # this is so that we can encode a long function into a symbol for cleaner code
    r <- substitute(f(x))
    
    tryCatch(
        list(eval(r), ""),
        error = function(e) return(list("", e)),
        warning = function(w) return(list(eval(r), w))
    )
}

custom_f(9)
## [[1]]
## [1] 9
## 
## [[2]]
## [1] ""
custom_f(20)
## Warning in f(20): Number is bigger than 10.
## [[1]]
## [1] 20
## 
## [[2]]
## <simpleWarning in f(20): Number is bigger than 10.>
custom_f("20")
## [[1]]
## [1] ""
## 
## [[2]]
## <simpleError in f("20"): Not a number!>