user32259
user32259

Reputation: 1143

R: how to add arguments to a function (in particular `...`)?

I think the following bit of code provides motivation for the question:

add <- function(x, y = 1) x + y
subtract <- function(x, z = 1) x - z
both <- function(x, ...) list(add(x, ...), subtract(x, ...))

both(1) 
# OK
both(1, z = 2)
# Error in add(x, ...) : unused argument (z = 2)

# a solution from a previous question I asked
add <- function(x, y = 1, ...) x + y
subtract <- function(x, z = 1, ...) x - z
both(1, z = 2)

So I'm looking for a function operator called add_dots say, which takes a function f, and returns f but with ... added to its list of arguments

Cheers for any help

Upvotes: 3

Views: 153

Answers (1)

alexis_laz
alexis_laz

Reputation: 13122

This seems to work:

add <- function(x, y = 1) x + y
#> add
#function(x, y = 1) x + y
formals(add) <- c(formals(add), alist(... = ))
#> add
#function (x, y = 1, ...) 
#x + y

After @agstudy 's comment, a function for it:

add_dots <- function(FUN)
{
 f <- match.fun(FUN)
 formals(f) <- c(formals(f), alist(... = ))
 return(f)
}

add <- function(x, y = 1) x + y
#> add
#function(x, y = 1) x + y
add_dots(add)
#function (x, y = 1, ...) 
#x + y
new.add <- add_dots(add)
#> new.add
#function (x, y = 1, ...) 
#x + y

Upvotes: 5

Related Questions