Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access all function arguments in R

Tags:

r

I've a function f() that has some named parameters. It calls a function g() and I want to pass all f's parameters to it. Is this possible?

Using ... just covers the extra arguments:

f=function(a,callback,b,c,d,...){
  z=a-b
  callback(z,...) 
  }

g=function(z,...){
  print(list(...))    #Only shows $e
  print(z)    #-1
  print(a,b,c,d)  #'a' not found   
}

f(1,g,2,3,d=4,e=5);

I thought formals() was the answer, but it just seems to be argument names, not their values!

f=function(a,callback,b,c,d,...){
  z=a-b
  callback(z,formals()) 
  }

g=function(z,...){
  args=list(...)[[1]]
  print(args$a) #(no output)
  print(class(args$a))  #"name"
}

f(1,g,2,3,d=4,e=5);

Is it possible? Thanks.

like image 531
Darren Cook Avatar asked Dec 05 '11 11:12

Darren Cook


People also ask

How do you find function arguments in R?

Get the List of Arguments of a Function in R Programming – args() Function. args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.

What does list () in R do?

The list() function in R is used to create a list of elements of different types. A list can contain numeric, string, or vector elements.

What type of arguments can a function take in R?

Function arguments in R can have default values. Default arguments can even be defined in terms of variables created within the function. This is used frequently in base R functions, but I think it is bad practice, because you can't understand what the default values will be without reading the complete source code.


1 Answers

Well, something like this is certainly possible. You should just figure our for yourself in which frame / point you'd like to evaluate the arguments of f which are then forwarded to g.

The typical procedure consists of match.call() call inside f to actually record the call expression which f was called with, then changing the call expression as it should be convenient for you (e.g. filtering out unnecessary args, adding new, etc.) and then evaluation of the new call expression via eval() call. So, something like this should (almost) work:

f <- function(a, callback, b, c, d, ...) {
  # Grab the "f" call expression
  fcall <- match.call(expand.dots = FALSE)

  # Construct the new call expression
  fcall[[1]] <- callback
  # Filter out / add new args
  fcall$callback <- NULL
  fcall$z <- z

  # Do the call
  eval(fcall, parent.frame())
}
like image 58
Anton Korobeynikov Avatar answered Sep 22 '22 06:09

Anton Korobeynikov