V1: Suppose functions f(x, ...)
and g(x , ...)
can be passed different arguments. If I were to define a new function using both of them, can I make the passing of arguments via the ...
operator well-defined? As a simple example:
f1 = function(x, n = 1) x + n
g1 = function(x, m = 1) x + m
f = function(x, ...) f1(x, ...)
g = function(x, ...) g1(x, ...)
h = function(x, ...) {
fgList = list()
fgList[["f"]] = f(x, ...)
fgList[["g"]] = g(x, ...)
return(fgList)
}
h(1:4)
# $f
# [1] 2 3 4 5
# $g
# [1] 2 3 4 5
h(1:4, n = 2)
# Error in g1(x, ...) : unused argument (n = 2)
The argument n
is being passed down to functions f
and g
, but it is only well-defined for function f
. I want to mitigate against this.
V2: If they are functions that I have defined, then Hong Ooi's solution below works perfectly.
Can this solution be extended for pre-defined functions which don't have a ...
argument or equivalently, can a ...
argument be 'added' to a predefined function which doesn't have one? For example:
h = function(x, ...) mean(x, ...) * median (x, ...)
h(1:4, test = 1)
## Error in median(x, ...) : unused argument (test = 1)
You can't have multiple versions of ...
in the one environment. What you can do, however, is give each of your called sub-functions a ...
argument of their own. This means they will ignore any parameters passed down that don't match their own formal arguments.
f1 = function(x, n = 1, ...) x + n
g1 = function(x, m = 1, ...) x + m
> h(1:4, n = 2)
$f
[1] 3 4 5 6
$g
[1] 2 3 4 5
Edit to answer added question: you can make a new version of median
, which will override the predefined function when you call it in your own code. (Due to how R namespaces work, other predefined functions will still use the existing version.)
median <- function(x, na.rm=FALSE, ...)
base::median(x, na.rm) # function median exported from base package
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With