[R] global objects not overwritten within function

bogdan romocea br44114 at yahoo.com
Wed Jan 12 21:04:37 CET 2005


Apparently the message below wasn't posted on R-help, so I'm sending it
again. Sorry if you received it twice.

--- bogdan romocea <br44114 at yahoo.com> wrote:

> Date: Tue, 11 Jan 2005 17:31:42 -0800 (PST)
> From: bogdan romocea <br44114 at yahoo.com>
> Subject: Re: [R] global objects not overwritten within function

Thank you to everyone who replied. I had no idea that ... means
something in R, I only wanted to make the code look simpler. I'm
pasting below the functional equivalent of what took me yesterday a
couple of hours to debug. Function f() takes several arguments (that's
why I want to have the code as a function) and creates several objects.
I then need to use those objects in another function fct(), and I want
to overwrite them to save memory (they're pretty large).

It appears that Robert's guess (dynamic/lexical scoping) explains
what's going on. I've noticed though another strange (to me) issue:
without indexing (such as obj1 <- obj1[obj1 > 0] - which I need to use
though), fct() prints the expected values even without removing the
objects after each iteration. However, after indexing is introduced,
rm() must be used to make fct() return the intended output. How would
that be explained?

Kind regards,
b.

f <- function(read,position){
obj1 <- 5 * read[position]:(read[position]+5)
obj2 <- 7 * read[position]:(read[position]+5)
assign("obj1",obj1,.GlobalEnv)
assign("obj2",obj2,.GlobalEnv)
}
fct <- function(input){
for (i in 1:5)
	{
	f(input,i)
	obj1 <- obj1[obj1 > 0]
	obj2 <- obj2[obj2 > 0]
	print(obj1)
	print(obj2)
#	rm(obj1,obj2)	#get intended results with this line
	}
}
a <- 1:10
fct(a)




More information about the R-help mailing list