How to know the arguments contained in '...' in a function in R?

7

In R you can use '...' for the function to receive an indeterminate number of arguments.

How do I know which arguments were used in the function?

Example, if I wanted to print the arguments used.

imprimeArgumentos <- function(...) {
  args <- #pega os argumentos contidos em ´...´
  print(args)
}

The function should work as follows.

imprimeArgumentos(x=3, z=NULL, y=3) 

$x
[1] 3

$z
NULL

$y
[1] 3
    
asked by anonymous 14.01.2016 / 14:02

1 answer

6

A simple way to capture the arguments is to put them in a list:

imprimeArgumentos <- function(...) {
  args <- list(...)
  print(args)
}

imprimeArgumentos(x=3, z=NULL, y=3) 
#> $x
#> [1] 3
#> 
#> $z
#> NULL
#> 
#> $y
#> [1] 3

If you want to work with lazy evaluation, you can use substitute and only evaluate arguments when appropriate:

imprimeArgumentos <- function(...) {
   # vai te retornar uma expressão da lista e não a lista em si
  args <- substitute(list(...))
  print(args)
}
imprimeArgumentos(x=3, z, y=3)
#> list(x = 3, z, y = 3)

Note that in this last example, z does not exist, but function does not give an error because we have not yet evaluated the contents of the list.

    
14.01.2016 / 14:10