[R] global objects not overwritten within function

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Jan 11 18:01:21 CET 2005


On Tue, 11 Jan 2005, bogdan romocea wrote:

> Dear useRs,
>
> I have a function that creates several global objects with
> assign("obj",obj,.GlobalEnv), and which I need to run iteratively in
> another function. The code is similar to
>
> f <- function(...) {
> assign("obj",obj,.GlobalEnv)
> }
> fct <- function(...) {
> for (i in 1:1000)
> 	{
> 	...
> 	f(...)
> 	...obj...
> 	rm(obj)	#code fails without this line
> 	}
> }
>
> I don't understand why f(), when run in a for() loop inside fct(), does
> not overwrite the global object 'obj'. If I don't delete 'obj' after I
> use it, the code fails - the same objects created by the first
> iteration are used by subsequent iterations.
>
> I checked ?assign and the Evaluation chapter in 'R Language Definition'
> but still don't understand why the above happens. Can someone briefly
> explain or suggest something I should read? By the way, I don't want to
> use 'better' techniques (lists, functions that return values instead of
> creating global objects etc) - I want to create global objects with f()
> and overwrite them again and again within fct().

Since you are not using ... in the sense it is used in R, we have little 
idea of what your real code looks like and so what it does.

Can you please give a small real example that fails.  Here is one that 
works, yet has all the features I can deduce from your non-code:

f <- function(x) assign("obj", x, pos=.GlobalEnv)
fct <- function()
{
    for(i in 1:2) {
      x <- i+3
      f(x)
      print(obj)
    }
}
> fct()
[1] 4
[1] 5
> obj
[1] 5

-- 
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-help mailing list