Skip to contents

You want to use a function if it is installed but don't want it to be installed as part of your package and you don't want to reference it as part of the Imports or Suggests fields in a package DESCRIPTION.

Usage

optional_fn(
  pkg,
  name,
  alt = function(...) {
     stop("function `", pkg, "::", name, "(...)` not available")

    }
)

Arguments

pkg

the package name (or the function name as "pkg::fn")

name

the function you wish to use (if not specified in pkg)

alt

an alternative function that can be used if the requested one is not available. The default throws an error if the package is not available, but a fallback can be used instead.

Value

the function you want if available or the alternative

Examples

# use openSSL if installed:
fn = optional_fn("openssl", "md5", alt = ~ digest::digest(.x, "md5"))

as.character(fn(as.raw(c(1,2,3))))
#> [1] "5289df737df57326fcdd22597afb1fac"

#' # this function does not exists and so the alternative is used instead.
fn3 = optional_fn("asdasdadsda::asdasdasd", ~ message("formula alternative"))
fn3()
#> formula alternative