How to call a function in R which I specify via the commandline? -
how do in r
:
i have sourced function name examplefoo
suppose:
examplefoo <- function(a, predefined, signature)
given character vector examplefoo
, how can use call function name?
it depends if going on inside function or @ top level. i'll take in reverse order.
examplefoo <- function(a, predefined, signature) { 1:10 } fun <- "examplefoo" get(fun) get(fun)() > get(fun) function(a, predefined, signature) { 1:10 } > get(fun)() [1] 1 2 3 4 5 6 7 8 9 10
in function, match.fun
argument applicable here. get
looks objects name supplied it, whereas match.fun
considers function objects when searching. has additional benefit of not matching non-function objects may have same name.
foo <- function(f) { bar <- match.fun(f) bar() } > foo(fun) [1] 1 2 3 4 5 6 7 8 9 10 > foo("examplefoo") [1] 1 2 3 4 5 6 7 8 9 10
you can't use match.fun
(easily?) @ top level designed perform matching in parent frame of caller , global environment doesn't have parent (iirc).
other examples
@agstudy suggests switch
based approach having wrapper function can call 1 of several pre-defined functions name. in comments there proposed 2 simpler alternatives. here expand upon that:
foo1 <- function(method, ...) { dots <- list(...) fun <- match.fun(method) do.call(fun, dots) }
or
foo2 <- function(method = c("fun1", "fun2", "fun3"), ...) { dots <- list(...) method <- match.arg(method) fun <- match.fun(method) do.call(fun, dots) }
i've written these pretty general functions take arguments plus method
. if functions reference / passed method
have ...
argument, these called directly, perhaps 1 or more named arguments, e.g.
## assuming `method` refers function first argument `x` , ## `...` argument foo3 <- function(method, x, ...) { fun <- match.fun(method) fun(x, ...) }
Comments
Post a Comment