有沒有所謂的「統計:: RNORM」功能。您必須在「統計」命名空間中找到rnorm
功能:
myfun <- get("rnorm", asNamespace("stats"))
myargs <- list(n=10, mean=5);
do.call(myfun, myargs);
現在,你當然也可以從一個名字去,如「統計:: 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);
更新我只是想證明,該方法是2.5倍的速度比從@Jeroen一...
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
如何關於'do.call(stats :: rnorm,myargs)'? – kohske 2012-04-05 04:26:51
@kohske - 然後它似乎'stats :: rnorm(n = 10,mean = 5)'更簡單:-) – Tommy 2012-04-05 05:16:49
但在這種情況下,你不能使用list作爲它的參數:-( – kohske 2012-04-05 05:18:17