[R] with() and within() functions inside lapply() not seeing outside of its environment?

Pavel N. Krivitsky pavel at uow.edu.au
Fri Jan 10 01:28:39 CET 2014


Hi,

> I wouldn't call it a bug, but it's a documented limitation, if you know 
> how to read it.  As documented, the expression is evaluated with the 
> caller's environment as the parent environment.  But here the caller is 
> some code in lapply, not your function f.  x is not found there.

Thanks! That explains it.

> I think this modification works, and is maybe the simplest way to get it 
> to work:
> 
> f <- function(x){
>    y <- list(y1=list())
>    mywithin <- function(...) within(...)
>    y <- lapply(y, mywithin, {z<-x})
>    y
> }
> 
> The idea here is that the calling frame of f is the environment of 
> mywithin(), so x is found there.

It works.

                    Best regards,
                    Pavel




More information about the R-help mailing list