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

Asked

Viewed 272 times

7

In R can be used '...' so that the function receives an undetermined number of arguments.

How to 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 shall function as follows:.

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

$x
[1] 3

$z
NULL

$y
[1] 3

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 make the Valuation of arguments when timely:

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 gives no error as we have not yet evaluated the content of the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.