1

Is it possible to get the information which arguments are expected by a function and then store it in a character vector?

I know args(foo) but it only prints this information and returns NULL.

Why do I need this?
I want to work with the three dot arguments (dot dot dot, ...) and pass it to different functions.

Let me explain...
The following simple case works.

data <- c(1:10)

cv <- function(x, ...) {
  numerator <- mean(x, ...)
  denominator <- sd(x, ...)
  
  return(numerator / denominator)
}

cv(data, na.rm = TRUE)

However, in a slightly different case, R will not figure out automatically which aruments match which function.

data <- c(1:10)

roundCv <- function(x, ...) {
  numerator <- mean(x, ...)
  denominator <- sd(x, ...)
  result <- round(numerator / denominator, ...)
  
  return(result)
}

roundCv(data, na.rm = TRUE, digits = 2)
# Error in sd(x, ...) : unused argument (digits = 2)

If I want to separate those arguments, it gets a little hairy. The approach is not generic but has to be adapted to all functions involved.

data <- c(1:10)

roundCv2 <- function(x, ...) {
  
  args <- list(...)
  args1 <- args[ names(args) %in% "na.rm"] # For mean/sd
  args2 <- args[!names(args) %in% "na.rm"] # For print
  
  numerator <- do.call("mean", c(list(x = x), args1))
  denominator <- do.call("sd", c(list(x = x), args1))
  tmp <- numerator / denominator
  
  do.call("round", c(list(x = tmp), args2))
}

roundCv2(data, na.rm = TRUE, digits = 2)

Is there a simple way to do this?!
If I would know the arguments each function expects, I could handle it generically. That's why I'm asking:

Is it possible to get the information which arguments are expected by a function and then store it in a character vector?

Daniel Hoop
  • 652
  • 1
  • 5
  • 16
  • 1
    You can use `formals()` to get a list like object back, bit it won't work for primitive functions. Like `names(formals(...))` – MrFlick Mar 16 '22 at 15:09
  • 1
    Similar to https://stackoverflow.com/questions/4124900/is-there-a-way-to-use-two-statements-in-a-function-in-r and https://stackoverflow.com/questions/5080972/using-multiple-ellipses-arguments-in-r – MrFlick Mar 16 '22 at 15:11

1 Answers1

0

A shout-out to MrFlick for pointing to similar questions and giving the answer in the comments.

You can use formals() to get a list like object back, bit it won't work for primitive functions. Like names(formals(...))

More details can be found here: https://stackoverflow.com/a/4128401/1553796

Daniel Hoop
  • 652
  • 1
  • 5
  • 16