Re: [R] Problems with eval() in connection with match.call()

From: Douglas Bates <dmbates_at_gmail.com>
Date: Tue 05 Jul 2005 - 10:33:22 EST

On 7/4/05, Søren Højsgaard <Soren.Hojsgaard@agrsci.dk> wrote:
> Dear all, I have a problem when passing parms from one function to another when the argument list is just '...'. Consider this example:
>
> foo<-function(){
> xx <- 111222
> bar(x=xx)
> }
> bar <- function(...){
> cl <- match.call(expand.dots=TRUE)
> print(cl)
> x <- eval(cl$x)
> print(x)
> }
> foo()
>
> > bar(x = xx)
> > Error in eval(expr, envir, enclos) : Object "xx" not found
>
> My expectation was, that xx would be evaluated to 111222 in foo before being passed on to bar, but obviously it is not so.

Welcome to the world of lazy evaluation. Arguments are evaluated only when needed (i.e. when first referenced) not at the time of building the function call. That's why the default value of an argument can depend on previously calculated results within the function.

> Should I do something explicitely in foo() to 'evaluate' xx or need I do something special in bar()??

Change the eval(cl$x) to eval(cl$x, parent.frame())

> bar

function(...){

    cl <- match.call(expand.dots=TRUE)
    print(cl)
    x <- eval(cl$x, parent.frame())
    print(x)
}
> foo()

bar(x = xx)
[1] 111222

> Thanks in advance, Søren
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Tue Jul 05 10:37:14 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:33:12 EST