Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a function return its name and arguments in R

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)"
like image 827
rnso Avatar asked Sep 29 '22 00:09

rnso


1 Answers

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"
like image 190
Tom Avatar answered Oct 10 '22 02:10

Tom