0

In R documentation, it explains that

The argument '...' can be used to allow one function to pass on argument settings to another.

I am not very sure how it works... In my imagination it is going to work like this:

Arithmetic <- function(x, ...) {
  calculate <- function(x, y = 1, operand = "add") {
    if (operand == "add") {return(x + y)}
    if (operand == "subtract") {return(x - y)}
    if (operand == "multiply") {return(x * y)}
    if (operand == "devide") {return(x / y)}
  }
  return(calculate(x, y, operand))
}
Arithmetic(x = 3, y = 4, operand = "subtract")
## [1] -1

while what happens is:

Error in calculate(x, y, operand) : object 'operand' not found

So exactly how ... works for user-defined functions in R?

Matthew Hui
  • 634
  • 5
  • 18
  • 1
    Related: [Usage of `…` (three-dots or dot-dot-dot) in functions](https://stackoverflow.com/questions/5890576/usage-of-three-dots-or-dot-dot-dot-in-functions) – markus Nov 07 '18 at 08:29

1 Answers1

0

This would be enough:

calculate <- function(x, y, operand = "add") {
  if (operand == "add") {return(x + y)}
  if (operand == "subtract") {return(x - y)}
  if (operand == "multiply") {return(x * y)}
  if (operand == "devide") {return(x / y)}
}

Output:

calculate(3, 4, "subtract")
[1] -1

This function would have as default the "add" operand, but you can change it to whatever you need.

Basically, if you have already defined parameters, there is no need for ... .

If you would want to include the ..., then you could start with something like:

calculate <- function(x, ...) {

  args_list <- list(...)

  if (args_list[[2]] == "add") {return(x + args_list[[1]])}
  if (args_list[[2]] == "subtract") {return(x - args_list[[1]])}
  if (args_list[[2]] == "multiply") {return(x * args_list[[1]])}
  if (args_list[[2]] == "devide") {return(x / args_list[[1]])}

}

calculate(3, 4, "subtract")
[1] -1
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • 1
    You are right in specifying the function, but the question focuses on the logic and use of the '...' argument. – Tomas Nov 07 '18 at 08:30
  • 1
    @Tomas true, but in this specific function I don't see the purpose of '...'. If the question is only regarding its use, then there are already several answers elsewhere on Stack. – arg0naut91 Nov 07 '18 at 08:32