Reputation: 3648
How is it possible to access evaluated arguments to a function in case arguments have missing values.
Assuming the function is defined like.
foo <- function(...){
# function body
}
How to access arguments to function in its body, if some arguments are missing?
In case of no missing value, the answer is just
foo <- function(...){
args <- list(...)
}
But this will not work if we do a call like foo(1,,3)
.
And other way I was able to find
foo <- function(...){
args <- as.list(match.call())[-1]
}
Gives a list of arguments but they are not evaluated. For example for call foo(rnorm(10), 1, 2)
args will contain unevaluated arguments, that I have sometimes troubling evaluating.
Is there any meaningful way to do this?
UPD I need this because I want to write a wrapper functions that record arguments to function calls and return values. For example,
matrix_w <- function(...){
args <- list(...)
res <- matrix(...)
return(res)
}
In a case of most calls it will work, but for call matrix_w(rnorm(20), , 2)
, it will not be able to process arguments in args <- list(...)
, but matrix(rnorm(20), , 2)
works correctly.
Upvotes: 0
Views: 151
Reputation: 206232
If you want them evaluated, you probably just should evaluate them yourself
matrix_w <- function(...){
args <- as.list(match.call())[-1]
eval.args <- lapply(args, function(x) tryCatch(eval(x), error=function(z) x))
do.call(matrix, eval.args)
}
matrix_w(rnorm(10), , 2)
Upvotes: 1