[R] variable scope
Marc Schwartz
marc_schwartz at me.com
Tue Aug 28 20:51:32 CEST 2012
On Aug 28, 2012, at 1:29 PM, Sam Steingold <sds at 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
More information about the R-help
mailing list