This got rejected by SpamCop but I didn't see another reply so am trying again.
-----Original Message----- From: Huntsinger, Reid Sent: Wednesday, January 12, 2005 4:29 PM To: 'bogdan romocea'; [email protected] Subject: RE: [R] global objects not overwritten within function Assigning via <- to "obj1" and "obj2" in fct() creates local copies. In the next iteration "obj1[obj1 > 0]" and "obj2[obj2 > 0]" refer to these local copies, unless you remove them, not the ones in .GlobalEnv, as you intend. You can also use "get" to specify which environment to look in. Reid Huntsinger -----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of bogdan romocea Sent: Wednesday, January 12, 2005 3:05 PM To: [email protected] Subject: Re: [R] global objects not overwritten within function Apparently the message below wasn't posted on R-help, so I'm sending it again. Sorry if you received it twice. --- bogdan romocea <[EMAIL PROTECTED]> wrote: > Date: Tue, 11 Jan 2005 17:31:42 -0800 (PST) > From: bogdan romocea <[EMAIL PROTECTED]> > 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) ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
