1

Suppose I have a function in my environment defined as follows:

abc <- function(x, a, b=23) { return(paste(x, a, b, sep=';')) }

I would like to get a reference to the above function by its name in the environment and be able to call it replacing its parameters. So an example:

> fun.abc <- get.fun.from.env('abc')  #`fun.abc` should be the same as `abc` (above)
> x <- 123
> addl.params <- c(a=245, b=345)
> do.call(fun.abc, list(x, addl.params))
123;245;345

How would I implement this idea?

2
  • I'm not sure, but perhaps you are looking for get("abc")? Just curious: why can't you use abc as function instead of fun.abc? Commented May 15, 2020 at 14:49
  • I have a table in a database that dictates which function to load. I would like to only store the function name and some default params in the database. Commented May 15, 2020 at 14:54

2 Answers 2

2

do.call will accept a function name as a string so:

fun.name <- "abc"
do.call(fun.name, c(x, as.list(addl.params)))
## [1] "123;245;345"

You may need to specify the envir= argument of do.call if fun.name is not in an environment reachable from the do.call.

Sign up to request clarification or add additional context in comments.

4 Comments

That is exactly what I did in my answer below. It's not exactly what I am looking for. I would like to pass around a pointer to the function.
As I read the question it is asking how to run a function given its name as a character string and the answer here shows how to do that in one line of code. If your question is how to get the function from its name then get(fun.name) will do it. You might need to clarify the question if those are not your question.
oh, ok, yes, that's what I was looking for - didn't know it was as simple as: fun <- `get('abc'). But then how would I call fun using dynamic arguments. I'll try to clarify my question more...
get works for any object so x <- 3; xname <- "x"; get(xname) retreives x, i.e. 3.
0

*** UPDATE. After brief discussion with G. Grothendieck I see how to do it now:

> fun.abc <- get('abc')
> x <- 123
> addl.params <- c(a=245, b=345)

#somewhere else when I have a pointer to fun.abc
> do.call(fun.abc, c(x, as.list(addl.params)))

*** THIS WAS MY FIRST ATTEMPT AT THIS:

I came close to what I wanted to do in a somewhat different way. Hoping someone might be able to propose a way to achieve what I originally intended...

apply.fun <- function(func.id, x, ...) {
  func.def <- load.func.spec.from.db(func.id)
  def.args <- eval(str2lang(func.def$params))
  args <- replace(def.args, names(...), as.list(...))

  do.call(func.def$fun, list(x=x, unlist(args)))
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.