Functions with number of arguments "dynamic"

4

I want to construct a function that can have the number of variable parameters, such as the c function, and how to access their addresses, for example:

c(a = 1, b = 2, d = 9)
#acessar a, b e d

Is it related to ... ? What do they mean?

    
asked by anonymous 23.06.2016 / 19:01

2 answers

7

dot-dot-dot or ... is called ellipse .

minha_funcao_com_elipse <- function(...) {
  input_list <- list(...)
  input_list
}

See the result of this function:

> minha_funcao_com_elipse(a = 1, b= 2, c= 3)
$a
[1] 1

$b
[1] 2

$c
[1] 3

Note that the input_list <- list(...) command creates a list of all the parameters that were passed within the ellipse .

Since input_list is a common list of R, it's easy to access its elements. The c function, for example could be imitated as follows:

> c2 <- function(...) {
+   unlist(list(...))
+ }
> c2(a = 1, b= 2, c= 3, 5, 6)
a b c     
1 2 3 5 6 

It pays to read this SO response . Another good reference is Advanced R in session ... .

    
23.06.2016 / 19:09
6

You can define a function using ... , which can be used to access arguments passed explicitly by name. To access the values, you convert ... to a list (using list(...) ). The code below shows an example:

c <- function(...) {
    args <- list(...)
    argNames <- names(args)
    print(argNames)
    sum(sapply(args, function(x) x))
}

c(a = 1, b = 4, d = 9)
    
23.06.2016 / 19:10