how to make all arguments of a function named in r

In R, you could use "..." (ellipsis) to capture unspecified arguments in a function. To name all the arguments using ellipsis, you can use the match.call() and as.list() functions to create a named list of arguments.

Here is an example:

main.r
my_fun <- function(...){
  args <- as.list(match.call())[-1] # capture arguments as named call
  names(args) <- sapply(args, deparse) 
  # deparse function names
  # set names to each argument
  return(args)
}

#Testing function call

my_fun(a=1,b=2,c=3)
my_fun(x=1,y=2,z=3, w = 4)
my_fun(1,2,3)
296 chars
14 lines

The output will be:

main.r
$a
[1] 1

$b
[1] 2

$c
[1] 3
29 chars
9 lines
main.r
$x
[1] 1

$y
[1] 2

$z
[1] 3

$w
[1] 4
39 chars
12 lines
main.r
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3
38 chars
9 lines

In the first call my_fun(a=1,b=2,c=3), the named arguments in the function call a=1, b=2, c=3 are captured as a named list.

In the second call my_fun(x=1,y=2,z=3, w = 4), the function is called with 4 named arguments, which are captured and returned as a named list.

In the third call my_fun(1,2,3), only the values are passed to the function without naming them. The unnamed values are assigned with indexes ([[1]], [[2]], [3]) in the list, with no corresponding names.

gistlibby LogSnag