How do I call a namespaced function without evaluating the parameters you are giving it?

In R, the idiomatic way to call another function without evaluating the parameters you give it is apparently as follows:

Call <- match.call(expand.dots = TRUE)
# Modify parameters here as needed and set unneeded ones to NULL.
Call[[1L]] <- as.name("name.of.function.to.be.called.here")
eval.parent(Call)

However, when I put a namespaced name (e.g. utils::write.csv) in the as.name() call, I get an error:

"could not find function "utils::write.csv"

What is the proper way of using this R idiom to call a namespaced function?

Answers


Here is a solution using do.call(), which both constructs and evaluates the function call.

Like the approach you started with, this one uses the fact that R calls are lists in which: (a) the first element is the name of a function; and (b) all following elements are arguments to that function.

j <- function(x, file) {
    Call <- match.call(expand.dots = TRUE)
    arglist <- as.list(Call)[-1]
    do.call(utils::write.csv, arglist)
}

dat <- data.frame(x=1:10, y=rnorm(10))

j(dat, file="outfilename.csv")

EDIT: FWIW, here's an example from plot.formula in base R, which uses a construct similar to the one above:

{
    m <- match.call(expand.dots = FALSE)
    eframe <- parent.frame()
    . . .
    . . . 
    m <- as.list(m)
    m[[1L]] <- stats::model.frame.default
    m <- as.call(c(m, list(na.action = NULL)))
    mf <- eval(m, eframe)
    . . .
    . . . 
}

The function uses the do.call() construct later on. Going a bit deeper into the weeds, my reading is that in the snippet shown here, it instead uses several steps mostly because of the need to add na.action=NULL to the list of arguments.

In any case, it looks like the do.call() options is as close to canonical as could be desired.


Need Your Help

C++ operator compilation error

c++ xcode operator-overloading llvm

I'm trying to compile a project which uses OpenCV C++ code in Xcode.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.