wibeasley
wibeasley

Reputation: 5287

Using R's `get()` function, while qualifying with the package

I'd like to assign a function to variable, using a string. The get() function in the base package does almost exactly what I want. For example,

valueReadFromFile <- "median"
ds <- data.frame(X=rnorm(10), Y=rnorm(10))
dynamicFunction <- get(valueReadFromFile)
dynamicFunction(ds$X) #Returns the variable's median.

However, I want to qualify the function with its package, so that I don't have to worry about (a) loading the function's package with library(), or (b) calling the wrong function in a different package.

Is there a robust, programmatic way I can qualify a function's name with its package using get() (or some similar function)? The following code doesn't work, presumably because get() doesn't know how to interpret the package name before the ::.

require(scales) #This package has functions called `alpha()` and `rescale()`
require(psych) #This package also has functions called `alpha()` and `rescale()`

dynamicFunction1 <- get("scales::alpha")
dynamicFunction2 <- get("psych::alpha")

Upvotes: 0

Views: 214

Answers (2)

mnel
mnel

Reputation: 115390

You can also call :: directly with character values, or getExportedValue, which :: uses internally

eg

dynamicFunction1 <- `::`('scales', 'alpha')
dynamicFunction2 <- `::`('psych', 'alpha')

or

dynamicFunction1 <-  getExportedValue('scales', 'alpha')
dynamicFunction2 <-  getExportedValue('psych', 'alpha')

Upvotes: 2

IRTFM
IRTFM

Reputation: 263362

Try this:

dynamicFunction1 <- get("alpha", envir=as.environment("package:scales"))
dynamicFunction2 <- get("alpha", as.environment("package:psych"))

A matter of terminology: I would not call dynamicFunction1 a "variable" but rather a "name". There is not really a formal class of object named "variable" but I usually see that term used for data-objects whereas "names" are language objects.

Upvotes: 3

Related Questions