On 28/08/2012 2:29 PM, Sam Steingold 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?
You should put most code in functions, so i and x will be locals and
will be automatically collected when your function returns. You rarely
need to call gc() explicitly; R will do automatic collections.
There are exceptions to the automatic collection. For example, if your
return value is a function, its environment will include all the locals,
and they will persist as long as the returned function does. If you
have big local values like your x and you don't need them as part of the
environment of your function, then you might want to remove them
explicitly. The only reason I ever call gc() is for debugging, but
others may have good reasons for asking space to be freed sooner rather
than later.
Duncan Murdoch
______________________________________________
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.