Skip to content

Method to call downstream function with appropriate ... args? #43

@jmw86069

Description

@jmw86069

Due respect, I'm not sure if this is the best place to ask the question.

Scenario:

  • Parent function passes ... to one or more downstream functions.
  • Downstream function does not allow ..., and has a lot of arguments (83).
  • Parent function would like to allow ... for customization of downstream function.
  • Parent function would like to pass only appropriate ... arguments to downstream function, to avoid causing an error.

From section 6.2.4 https://adv-r.hadley.nz/functions.html#function-fundamentals it appears that do.call(function, args) could be used for this purpose. I wonder if some type of function would live in this package?

Example scenario:

my_lil_function <- function(x, ...) {
   mean_function(x, ...)
}
mean_function <- function(x, na.rm=FALSE) {
   mean(x, na.rm=na.rm)
}
# success
my_lil_function(c(1, 2.5, 3, NA), na.rm=TRUE)
# error
my_lil_function(c(1, 2.5, 3, NA), na.rm=TRUE, color="red")
# Error in mean_function(x, ...) : unused argument (color = "red")

Rough idea of workaround:

# new function for this package?
call_fn_ellipsis <- function(FUN, ...) {
   FUN_argnames <- names(formals(FUN));
   if ("..." %in% FUN_argnames) {
      # if FUN allows ... then pass all of ...
      FUN(...)
   } else {
      # if FUN does not allow ... then pass only what it accepts
      arglist <- list(...)
      argkeep <- which(names(arglist) %in% FUN_argnames)
      arguse <- arglist[argkeep]
      do.call(FUN, arguse)
   }
}

# new method would involve using do.call()
my_new_lil_function <- function(x, ...) {
   args_to_send <- c(list(x=x),
      list(...));
   do.call(call_fn_ellipsis,
      c(FUN=mean_function, args_to_send))
}
# now success
my_new_lil_function(c(1, 2.5, 3, NA), na.rm=TRUE, color="red")
# [1] 2.17

Main drivers:

  • I don't want to add 83 arguments to my_lil_function() in order to avoid using ...
  • I want to use ... for customizations to two different functions called by my_lil_function()
  • I do not control the downstream function, so I can't add ... to that function's arguments.

Suggestions, feedback, guidance welcomed!
Maybe there is an R package function that already performs this step.
Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions