[R] variable scope
R. Michael Weylandt
michael.weylandt at gmail.com
Tue Aug 28 20:45:35 CEST 2012
On Tue, Aug 28, 2012 at 1:37 PM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
> On Tue, 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?
>
> Wrap the loop in local() scope perhaps? This might get tricky if you
> need to save some results from the loop, but I think you're ok if they
> are initialized outside the loop and you use super-assignment. Almost
> always you shouldn't need manual garbage collection.
>
> Something like: # Terribly impractical, but gets the point across
>
> y <- numeric(100)
> local({
> for(i in 1:10){
> x <- rnorm(10)
> y[10*(i-1) + 1:10] <<- x
> }
> })
>
> print(x) # Error
> print(y)
>
> Doubt that works out to be significantly more elegant however.
Elaborating a little more: the difficulty in this approach is that, if
you need results from the loop in a variable (instead of just doing
something n times and printing the results), you need R to know which
variables you intend to keep and which can be thrown away in the loop:
since a loop doesn't define its own scope like some languages (a
practice that always seemed strange to me), you have to resort to
tricks like `<<-` to move variables outside the local() scope.
The other answer is to use functions / apply statements like the good
lord and John Chambers intended :-)
M
>
> Michael
>
>>
>> Thanks.
>>
>> --
>> Sam Steingold (http://sds.podval.org/) on Ubuntu 12.04 (precise) X 11.0.11103000
>> http://www.childpsy.net/ http://camera.org http://palestinefacts.org
>> http://iris.org.il http://www.PetitionOnline.com/tap12009/ http://truepeace.org
>> Computers are like air conditioners: they don't work with open windows!
>>
>> ______________________________________________
>> R-help at 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.
More information about the R-help
mailing list