我大量使用'do.call'来生成函数调用。 E.g:
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);
答案 0 :(得分:19)
没有名为“stats :: rnorm”的功能。您必须在“stats”命名空间中找到rnorm
函数:
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
答案 1 :(得分:16)
你可以删除引号:这将是函数本身,而不是它的名称。
myfun <- stats::rnorm
myargs <- list(n=10, mean=5)
do.call(myfun, myargs)
答案 2 :(得分: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()来存储调用某处,它将保留实际的函数名称。 E.g:
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