20

我大量使用“do.call”来生成函数调用。例如:

myfun <- "rnorm";
myargs <- list(n=10, mean=5);
do.call(myfun, myargs);

但是,有时我想从某个包中显式调用一个函数。类似于例如stats::rnorm(n=10, mean=5)。有什么方法可以使用 do.call,或者创建一个行为类似于 do.call 的函数来使其工作:

myfun <- "stats::rnorm";
myargs <- list(n=10, mean=5);
do.call(myfun, myargs);
4

3 回答 3

23

没有名为“stats::rnorm”的函数。您必须rnorm在“stats”命名空间中找到该函数:

myfun <- get("rnorm", asNamespace("stats"))
myargs <- list(n=10, mean=5);
do.call(myfun, myargs);

现在,您当然也可以使用“stats::rnorm”之类的名称并将其拆分为命名空间部分和函数名称:

funname <- "stats::rnorm"
fn <- strsplit(funname, "::")[[1]]
myfun <- if (length(fn)==1) fn[[1]] else get(fn[[2]], asNamespace(fn[[1]]))
myargs <- list(n=10, mean=5);
do.call(myfun, myargs);

更新我只是想表明这种方法比@Jeroen 的方法快 2.5 倍......

do.call.tommy <- function(what, args, ...) {
  if(is.character(what)){
    fn <- strsplit(what, "::")[[1]]
    what <- if(length(fn)==1) {
        get(fn[[1]], envir=parent.frame(), mode="function")
    } else {
        get(fn[[2]], envir=asNamespace(fn[[1]]), mode="function")
    }
  }

  do.call(what, as.list(args), ...)
}

# Test it
do.call.tommy(runif, 10)
f1 <- function(FUN) do.call.tommy(FUN, list(5))
f2 <- function() { myfun<-function(x) x; do.call.tommy(myfun, list(5)) }
f1(runif)
f1("stats::runif")
f2()

# Test the performance...    
system.time(for(i in 1:1e4) do.call.jeroen("stats::runif", list(n=1, max=50))) # 1.07 secs
system.time(for(i in 1:1e4) do.call.tommy("stats::runif", list(n=1, max=50)))  # 0.42 secs
于 2012-04-05T03:58:25.347 回答
16

您可以删除引号:这将是函数本身,而不是它的名称。

myfun <- stats::rnorm
myargs <- list(n=10, mean=5)
do.call(myfun, myargs)
于 2012-04-05T04:02:30.843 回答
0

感谢您的回复。我想我会这样做:

do.call.jeroen <- function(what, args, ...){
  if(is.function(what)){
    what <- deparse(as.list(match.call())$what);
  }
  myfuncall <- parse(text=what)[[1]];
  mycall <- as.call(c(list(myfuncall), args));
  eval(mycall, ...);
}

这似乎是一个很好的概括,do.call因此我仍然可以为参数传递一个字符串what,但它巧妙地模拟了一个stats::rnorm(n=10, mean=5)调用。

myfun1 <- "rnorm";
myfun2 <- "stats::rnorm";
myargs <- list(n=10, mean=5);
do.call.jeroen(myfun1, myargs);
do.call.jeroen(myfun2, myargs);
do.call.jeroen(rnorm, myargs);
do.call.jeroen(stats::rnorm, myargs);

这样做的好处是,如果我正在调用的函数使用 match.call() 将调用存储在某处,它将保留实际的函数名称。例如:

do.call.jeroen("stats::glm", list(formula=speed~dist, data=as.name('cars')))

Call:  stats::glm(formula = speed ~ dist, data = cars)

Coefficients:
(Intercept)         dist  
     8.2839       0.1656  

Degrees of Freedom: 49 Total (i.e. Null);  48 Residual
Null Deviance:      1370 
Residual Deviance: 478  AIC: 260.8 
于 2012-04-05T23:36:53.473 回答