Suppose we have a function that makes a call to stats::lm and takes a formula and a data frame as arguments. Further arguments that we want to pass to stats::lm can be provided using variable arguments:
outer_function <- function(formula, data, ...) {
z <- stats::lm(formula = formula, data = data, ...)
return(z)
}
Now suppose we want to use this function and provide an additional argument (weights) that will be passed to stats::lm.
data <- data.frame(replicate(5, rnorm(100)))
weights <- replicate(100, 1)
formula <- X1 ~ X2 + X3
outer_function(formula = formula, data = data, weights = weights)
This produces the following error in stats::lm:
Error in eval(extras, data, env) :
..1 used in an incorrect context, no ... to look in
Debugging the call to stats::lm I see that argument weights is correctly passed to stats::lm, but match.call(), which is later used for evaluation in the function, is
stats::lm(formula = formula, data = data, weights = ..1)
such that weights is assigned the first element of the ...-list, which is empty.
Can anybody elaborate on why this approach fails? In particular, if weights was a scalar (say 5) the problem would not arise and the match.call() would be
stats::lm(formula = formula, data = data, weights = 5)
For now, I am using the following solution for my function:
outer_function <- function(formula, data, ...) {
args <- list(formula = formula, data = data, ...)
z <- do.call(stats::lm, args)
return(z)
}
which works but I am still wondering whether there is no way around do.call in case the arguments in ... are vectors or lists.