[R] variable scope

Duncan Murdoch murdoch.duncan at gmail.com
Tue Aug 28 21:01:13 CEST 2012


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




More information about the R-help mailing list