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

peter dalgaard pdalgd at gmail.com
Tue Jan 7 19:51:02 CET 2014


On 07 Jan 2014, at 19:19 , Duncan Murdoch <murdoch.duncan at gmail.com> wrote:

> 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.

I'd also consider it a bit brave to rely on ...-args to lapply being passed down unevaluated, but that does apparently work. 

At any rate, you cannot both have x evaluated in the frame of f, and the assignment to z _not_ evaluated there.

> 
> 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
> }

There is also brute-force substitution:

> f <- function(x){
+  y <- list(y1=list())
+  y <- eval(bquote(lapply(y, within, {z<-.(x)})))
+  y
+ }
> f(1)
$y1
$y1$z
[1] 1



> 
> The idea here is that the calling frame of f is the environment of mywithin(), so x is found there.
> 
> Duncan Murdoch
> 
>> 
>>                    Thanks in advance,
>>                    Pavel
>> 
>> P.S. If I "hard-code" the value for x, i.e.,
>> 
>> f <- function(){
>>   y <- list(y1=list())
>>   y <- lapply(y, within, {z<-1})
>>   y
>> }
>> f()
>> 
>> it returns list(y1=list(z=1)) as expected.
>> 
>> P.P.S. with() has the same problem:
>> 
>> f <- function(x){
>>   y <- list(y1=list())
>>   w <- lapply(y, with, x)
>>   w
>> }
>> f(1)
>> 
>> produces the exact same error as within().
>> 
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com




More information about the R-help mailing list