[R] Question about substitute (and eval, parse and deparse)

Thomas Lumley tlumley at u.washington.edu
Wed Jan 23 19:28:27 CET 2002


On Wed, 23 Jan 2002, Henrik Bengtsson wrote:

> I would like to define a function at run-time, but I just can't make it
> work (please don't question why I want to do this, because that would be
> too much to explain). For example, I want to define the the following
> function
>
>   foo <- function(x) {
>     cat("Function", "foo", "was called with argument", x, ".\n")
>   }
>
> However, I would like to create similar function where 'foo' is replaced
> with say 'bar' and 'x' is replaced with 'object'. I'll use the variables
> 'name' and 'arg' for this purpose;
>
>   name <- "foo";
>   arg <- "x";
>
> Now I'll create the 'call' to be evaluate to define the new function:
>
>   call <- substitute(fcn <- function(arg) { cat("Function", name, "was
>    called with argument", arg, ".\n"); }, list=list(fcn=as.name(name),
>    arg=as.name(arg), name=name))

<and strange things happen>

There are two issues here. One is that you really should have
options(keep.source=FALSE) if you're going to do this sort of thing, for
the sake of all our sanity.

The other is that substitute() doesn't do formal arguments to functions.

g<-eval(substitute( function(x){x+1},  list(x=as.name("y")) ))
> g
function (x)
{
    y + 1
}

I don't think this is precisely a bug, but it can be surprising.  You need
to set the formals() explicitly or use parse(deparse()).

The `macros' example in the last R Newsletter involves creating functions
at runtime a bit like this. You might find it helpful, but I think the
easiest solution may be to find a way of not doing this.


	-thomas




-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list