Jack Tanner Jack Tanner - 3 months ago 7
R Question

do.call a function in R without loading the package

I want to

do.call
an (exported) function from a package. The function name is a character string like
"lme4::lmer"
.

# Works, but not what I need
library(lme4)
do.call("lmer", ...)
# Also works, but not what I need
lme4::lmer(...)
# Doesn't work:
do.call("lme4::lmer", ...)

Answer

You can't include :: in the string because :: is a function. That string isn't evaluated and parsed. do.call just assumes a function by that name exists. Just like ::, $ is also a function so this doesn't work either

a<-list(f=function(x) x+1)
do.call(a$f, list(4))
# [1] 5
do.call("a$f", list(4))
# Error in do.call("a$f", list(4)) : could not find function "a$f"

If you want to be able to find functions from namespaces, you can write a helper function that parses values when they contain ::

getfun<-function(x) {
    if(length(grep("::", x))>0) {
        parts<-strsplit(x, "::")[[1]]
        getExportedValue(parts[1], parts[2])
    } else {
        x
    }
}
getfun("lme4::lmer")

And this should work

do.call(getfun("lme4::lmer"), list(
    Reaction ~ Days + (Days | Subject), 
    quote(lme4::sleepstudy)))
Comments