Is there any way to get the name and arguments of a function from within itself. For example:
> MYFN = function(name='test', num = 5, abool=T){
+ return ("MYFN = function(name='test', num = 5, abool=T)")
+ }
>
> MYFN()
[1] "MYFN = function(name='test', num = 5, abool=T)"
I want to have a fn called getMyHeader() which should return the name and arguments of the function from which it is called:
> MYFN = function(name='test', num = 5, abool=T){
+ getMyHeader()
+ }
>
> MYFN()
[1] "MYFN = function(name='test', num = 5, abool=T)"
Or, following could also be helpful:
getMyHeader(MYFN)
[1] "MYFN = function(name='test', num = 5, abool=T)"
The key is the use of args to get the arguments(easier since we call it from outside the function we are interested in), and substitute(x) to pull in the name of the argument (i.e. the function's name). This is easier if you do it outside of the function itself.
You can create a function or method to produce this for you, if you pass it the function name.
Here is an example creating a generic called 'header' and a method that is used when header is given a function (this prevents accidental execution on non-functions):
header<-function(x){
UseMethod('header',x)
}
header.function <-function(x){
y<-list(args(x))
x<-as.character(substitute(x))
print(sprintf('%s=%s',x,y))
}
to test:
myfn<- function(name='name',num=6,abol='abol'){
return(name,num,abol)
}
header(myfn)
returns:
[1] "myfn=function (name = \"name\", num = 6, abol = \"abol\") \nNULL"
Note the escaped quotes (this is good for printing). Off the top, I forget how to strip this down, but it shouldn't be too difficult.
You can use this with any function:
header(glm)
returns:
[1] "glm=function (formula, family = gaussian, data, weights, subset, na.action, start = NULL, etastart, mustart, offset, control = list(...), model = TRUE, method = \"glm.fit\", x = FALSE, y = TRUE, contrasts = NULL, ...) \nNULL"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With