dingus
dingus

Reputation: 1001

Reference functions in an R package by package+function name

I'm working on an automation tool which receives R packages-under-development at a known folder (e.g. /src) and wants to run certain functions from the package within a broader context: For example running function do_a_thing().

One problem is that, although the package can be reliably loaded e.g. with devtools::load_all("src"), I don't know what package name the author might have put in the Package field of the DESCRIPTION file.

This means I can't just call src::do_a_thing(), because the actual form might be e.g. MyWeirdPackageName::do_a_thing().

I know the desc package supports looking up this package name:

library(desc)
desc <- description$new("src")
desc$get("Package")

# > Package: 'MyWeirdPackageName'

...and also that exists can check for existence of the target function in the package:

exists("do_a_thing", where=paste("package", desc$get("Package"), sep=":"), mode="function")

# > TRUE

...But how can I actually call this function given that I know (at runtime, as a character vector) its fully qualified name is MyWeirdPackageName::do_a_thing?

Vanilla get doesn't seem to be able to handle the namespace aspect either by accepting a where argument or taking a fully-qualified name as input:

testfn <- get(paste(desc$get("Package"), "::do_a_thing", sep=''), mode="function")

# > Error in get(paste(desc$get("Package"), "::do_a_thing", sep = ""), mode = "function"): object
#   'MyWeirdPackageName::do_a_thing' of mode 'function' was not found

How can I explicitly invoke the do_a_thing function from this package, given that I know it exists and the name of the package it lives in?

Upvotes: 0

Views: 279

Answers (1)

Kota Mori
Kota Mori

Reputation: 6750

I think you can use eval(parse(text="code here")) trick. For example,

mean(c(1,2,3,4))
#[1] 2.5

# is equivalent to

eval(parse(text="mean(c(1,2,3,4))"))
#[1] 2.5

So in your case, this would work.

eval(parse(text="MyWeirdPackageName::do_a_thing"))

If you can get your package name as string (I think you are already good with that), then you can substitute that like:

packagename <- "???"
eval(parse(text=paste0(packagename, "::do_a_thing")))

Upvotes: 1

Related Questions