Using the following function foo()
as a simple example, I'd like to distribute the values given in ...
two different functions, if possible.
foo <- function(x, y, ...) {
list(sum = sum(x, ...), grep = grep("abc", y, ...))
}
In the following example, I would like na.rm
to be passed to sum()
, and value
to be passed to grep()
. But I get an error for an unused argument in grep()
.
X <- c(1:5, NA, 6:10)
Y <- "xyzabcxyz"
foo(X, Y, na.rm = TRUE, value = TRUE)
# Error in grep("abc", y, ...) : unused argument (na.rm = TRUE)
It seems like the arguments were sent to grep()
first. Is that correct? I would think R would see and evaluate sum()
first, and return an error for that case.
Furthermore, when trying to split up the arguments in ...
, I ran into trouble. sum()
's formal arguments are NULL
because it is a .Primitive
, and therefore I cannot use
names(formals(sum)) %in% names(list(...))
I also don't want to assume that the leftover arguments from
names(formals(grep)) %in% names(list(...))
are to automatically be passed to sum()
.
How can I safely and efficiently distribute ...
arguments to multiple functions so that no unnecessary evaluations are made?
In the long-run, I'd like to be able to apply this to functions with a long list of ...
arguments, similar to those of download.file()
and scan()
.
...
values are sent to both function.sum(X, na.rm = TRUE, value = TRUE)
does not return an error (note thatsum(1, na.rm = TRUE, value = TRUE)==2
), butgrep("abc",Y, na.rm = TRUE, value = TRUE)
does.R will not change the...
based on what's actually used by a function. If you want to split up the parameters, you will have to do it by yourself. – MrFlick...
either for all or for all but one of the inner functions and usedo.call
;foo = function(x, y, sum_args = list(NULL), grep_args = list(NULL)) list(sum = do.call("sum", c(list(x), sum_args)), grep = do.call("grep", c(list("abc"), list(y), grep_args)))
;foo(c(1:5, NA, 6:10), "xyzabcxyz")
;foo(c(1:5, NA, 6:10), "xyzabcxyz", sum_args = list(na.rm = TRUE), grep_args = list(value = TRUE))
– alexis_lazformals(args(sum))
. – Richie Cotton