On Aug 28, 2012, at 1:29 PM, Sam Steingold <s...@gnu.org> wrote: > At the end of a for loop its variables are still present: > > for (i in 1:10) { > x <- vector(length=100000000) > } > ls() > > will print "i" and "x". > this means that at the end of the for loop body I have to write > > rm(x) > gc() > > is there a more elegant way to handle this? > > Thanks.
It is not clear why you want 'x' to be created and overwritten 10 times, but perhaps I am missing something. You end up with 1 'x' after the loop, not 10 objects. More generally, I can think of a few options, all of which use functions to create your desired object, so that there are no other objects created during execution. Use sapply() rather than a for() loop: NewObject <- sapply(seq(10), DoSomethingHere...) Use replicate(), which will return an array by default: NewObject <- replicate(10, DoSomethingHere...) Or...just create a function that takes requisite arguments and runs the for() loop within the function body and returns the object you actually need. That way, any variables created within the scope of the function are gone when the function exits. Regards, Marc Schwartz ______________________________________________ R-help@r-project.org 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.