[Rd] [R] function changes argument (PR#9216)
ripley at stats.ox.ac.uk
ripley at stats.ox.ac.uk
Mon Sep 11 13:32:58 CEST 2006
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:
> (This report appeared in R-help. I've sent it separately to the bugs
> list to avoid a long string of cross-postings.)
>
> On 9/11/2006 4:49 AM, Moeltner, Andreas wrote:
> > Dear R-list,
> >
> > the following function f changes L. I thought, assignments within
> > functions are only local?
>
> That looks like a bug, still present in R-patched and R-devel. (I
> haven't got the latest pre-release built yet today, but I expect it's
> there, too.) Thanks for the report.
>
> I'll send a copy of this to the bugs list, but I won't be able to
> attempt to fix it.
>
> Duncan Murdoch
>
> >
> >
> > f<-function(LL)
> > { for (ll in LL)
> > { ll$txt<-"changed in f"
> > }
> > }
> >
> > l<-list(txt="original value")
> > L<-list(l)
> > L[[1]]$txt
> > f(L)
> > L[[1]]$txt
> >
> >
> > gives (using R 2.3.1):
> >
> > ...
> >> L[[1]]$txt
> > [1] "original value"
> >> f(L)
> >> L[[1]]$txt
> > [1] "changed in f"
> >
> > Thanks in advance
> >
> > Andreas
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch 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-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-devel
mailing list