Skip to content
Prev 21898 / 63424 Next

function changes argument (PR#9216)

I can tell you where the problem is and a workaround:

f <- function(LL) for (ll in names(LL)) LL[[ll]]$txt<-"changed in f"

works.  The problem is that for() is directly exposing the elements of a 
list.

Of course, a more idiomatic construction would be

LL <- lapply(LL, function(x) x$txt <- "changed in f")

which also works.

The question is whether we do wish to change this to make the construction 
work as Andreas appears to intend.  The simplest solution is a 
precautionary duplicate in for(), which is potentially very expensive and 
almost always unneeded.

However, we already have

x <- 1:10
for(i in x) i <- pi
x

which does not change x, so I think the right solution is to make the list 
(LL here) read-only, which can be done cheaply.  That is also AFAICS what 
S does.
On Mon, 11 Sep 2006, murdoch at stats.uwo.ca wrote: