Using the following function foo()
as a simple example, I\'d like to distribute the values given in ...
two different functions, if possible.
You can only pass the ...
argument to another function, if that other function includes all named arguments that you pass to ...
or if it has a ...
argument itself. So for sum
, this is no problem (args(sum)
returns function (..., na.rm = FALSE)
). On the other hand grep
has neither na.rm
nor ...
as an argument.
args(grep)
# function (pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,
# fixed = FALSE, useBytes = FALSE, invert = FALSE)
This does not include ...
and also does not include a named argument na.rm
either. A simple solution is to just define your own function mygrep
as follows:
mygrep <- function (pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,
fixed = FALSE, useBytes = FALSE, invert = FALSE, ...)
grep(pattern, x, ignore.case, perl, value, fixed, useBytes, invert)
Then it seems to work:
foo <- function(x, y, ...){
list(sum = sum(x, ...), grep = mygrep("abc", y, ...))
}
X <- c(1:5, NA, 6:10)
Y <- "xyzabcxyz"
foo(X, Y, na.rm = TRUE, value = TRUE)
# $sum
# [1] 56
#
# $grep
# [1] "xyzabcxyz"