Say I have a bunch of functions, each with something likeMyFunction.1
, etc. I want to pass these functions into another function, which prints out a small repo
what about this:
deparse(quote(foo.bar))
You can get the unevaluated arguments of a function via match.call
. For example:
> x <- function(y) print(match.call()[2])
> x(lm)
lm()
Another approach would be to pass the names of the functions into your report function, and then get the functions themselves with the get()
command. For instance:
function.names <- c("which","all")
fun1 <- get(function.names[1])
fun2 <- get(function.names[2])
Then you have the names in your original character vector, and the functions have new names as you defined them. In this case, the all
function is now being called as fun2
:
> fun2(c(TRUE, FALSE))
[1] FALSE
Or, if you really want to keep the original function names, just assign them locally with the assign function:
assign(function.names[2], get(function.names[2]))
If you run this command right now, you will end up with the all
function in your ".GlobalEnv"
. You can see this with ls()
.
When a function is passed around as an object, it loses its name. See, for example, the results of the following lines:
str(lm)
lm
You can get the arguments and the body of the function, but not the name.
My suggestion would be to construct a named list of functions, where the name could be printed:
> somefns <- list(lm=lm, aggregate=aggregate)
> str(somefns)
List of 2
$ lm :function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
$ aggregate:function (x, ...)
> somefns[[1]](dist ~ speed, data=cars)
Call:
somefns[[1]](formula = dist ~ speed, data = cars)
Coefficients:
(Intercept) speed
-17.58 3.93
> names(somefns)[[1]]
[1] "lm"
That may lead to parse(eval(...))
at which point you are open for this critique:
R> library(fortunes)
R> fortune("parse")
If the answer is parse() you should usually rethink the question.
-- Thomas Lumley
R-help (February 2005)
R>
So do your functions have to be called MyFunction.1
etc pp?
I was wanting the same thing, and remembered library(foo)
didn't need quotes, this is what it does:
package <- as.character(substitute(package))