[R] Variables captured in closures get copied?

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Feb 11 19:59:42 CET 2009


Peter Dalgaard wrote:
> Titus von der Malsburg wrote:
>> Hi list!  I have a data frame called fix and a list of index vectors
>> called rois:
>>
>>   > head(rois, 3)
>>   [[1]]
>>   [1] 2 1
>>
>>   [[2]]
>>   [1] 3
>>
>>   [[3]]
>>   [1]  6  7 28 26 27 24 25
>>
>> The part that's causing the issue is the following line:
>>
>>   lapply(rois, function(roi) fix$x[roi] <- 100)
>>
>> So for every index vector I'd like to set the respective entries in the
>> data frame (fix) to 100.
>>
>> I expected the data frame would be changed after lapply but instead it
>> remains unchanged.  I understand that when I pass an argument into a
>> function it gets passed as a value and not as a reference.  But here fix
>> is not an argument but captured in the closure.  Do my questions are:
>> What's going on here and what is the idiomatic way of achieving my goal?
>>
>
> It's a local variable in the function. Not in principle different from
>
> function(roi) { fix <- fix ;  ... }
>
> You could use superassignment (<<-), but a simpler idiom is
>
> for (roi in rois) fix$x[roi] <- 100
>

interesting.  i'm not sure if this is something one should consider
obvious, though it does make sense.
actually, it seems that r gets caught by surprise on such sort of semantics:

d = data,frame(x=1:10^8)
(function() d$x[1] = 0)()

prints 'Error: cannot allocate vector of size 762.9 Mb' and stops
responding with 100% cpu (sometimes even 101, as reported by top, hehe)
occupied by r.

platform       i686-pc-linux-gnu          
arch           i686                       
os             linux-gnu                  
system         i686, linux-gnu            
status                                    
major          2                          
minor          8.0                        
year           2008                       
month          10                         
day            20                         
svn rev        46754                      
language       R                          
version.string R version 2.8.0 (2008-10-20)

vQ




More information about the R-help mailing list