gpt4 book ai didi

r - do.call 结合 "::"

转载 作者:行者123 更新时间:2023-12-03 21:10:38 30 4
gpt4 key购买 nike

我大量使用“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);

最佳答案

没有名为“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

关于r - do.call 结合 "::",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10022436/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com