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
Just want to provide an example to show the advantage and limitation in this issue:
I want to "save" a function with its name, as an option that would be used in another function:
R> foreach(..., .combine=test_fun) {...}
The test_fun
is the name of the function, and of course
R> mode(test_fun)
[1] "function"
When I use it in foreach, I just need the function name, while test_fun
can be an existing function (e.g. cbind
). So, test_fun
is assigned by
R> test_fun <- get('cbind')
or
R> test_fun <- assign('cbind', get('cbind'))
So, you got the function here
R> test_fun
function (..., deparse.level = 1)
.Internal(cbind(deparse.level, ...))
actually, the original name can't be maintained, so you have no way to convert test_fun
back to string "cbind"
.
R> deparse(substitute(test_fun))
[1] "test_fun"
I unfortunately need to deparse the foreach code so want the original name shown in the string. This means that the only way is to save 'cbind'
as a string and creating such a function object brings no benefit in this case.
Nice observation by @nfultz, so the answer to this thread's question would be :-
workingFunction <- Function(f)
{ functionName <- as.character(substitute(f)) }
Or
workingFunction <- Function(f)
{ functionName <- deparse(substitute(f)) }
All the other answers would simply return the parameter name itself ('f' in the example above) - I tried them all since I've been working on a function and experienced this issue of not being able to retrieve a function's name inside another function wherein the first is passed as parameter to the second function while calling it. Hope my answer helps to all those who might be stuck for the same!