Variables captured in closures get copied?
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
O__ ---- Peter Dalgaard ?ster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907