Programmatically switch package in `::` call in R

  • A+

I would like to be able in a call bar::foo(), to be able to programmatically switch the package bar so that the same syntax calls hello::foo().

An example:

  • Let's say I have three packages, parentPkg, childPkg1 and childPkg2.
  • In parentPkg I have a call to function childPkg1::foo()
  • foo() is also a function in childPkg2
  • I would like to be able, in parentPkg to use the :: operator to call foo() but to programatically switch the package name. Something like:

    dummy_pkg_name = ifelse(scenario=="child1", "childPkg1", "childPkg2") dummy_pkg_name::foo() 

Is it possible? How do I achieve it?

Some context

parentPkg is a function that interacts with a web application, takes some request and data and returns results from different statistical models depending on the scenarios.
Each scenario is quite complex and not everything can be generalised in parentPkg. For this reason, childPkg1 and childPkg2 (actually there are also 3 and 4) are sort of sub-packages that deals with the data cleaning and various alternatives for each scenario but return the same class of value.
The idea is that parentPkg would switch the package to the pertinent child depending on the scenario and call all of the necessary functions without having to write the same sequence for each child but just with a slightly different :: call.


Since :: can be seen as a function, it looks like

`::`(dummy_pkg_name, foo)() 

is what you want. Alternatively,

getFromNamespace("foo", ns = dummy_pkg_name)() 

For instance,

`::`(stats, t.test) # function (x, ...)  # UseMethod("t.test") # <bytecode: 0x102fd4b00> # <environment: namespace:stats>  getFromNamespace("t.test", ns = "stats") # function (x, ...)  # UseMethod("t.test") # <bytecode: 0x102fd4b00> # <environment: namespace:stats> 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: