[R] Variable scoping question

David Winsemius dwinsemius at comcast.net
Thu Sep 8 15:31:34 CEST 2011


On Sep 8, 2011, at 9:13 AM, Bos, Roger wrote:

> I modified an example in the object.size help page to create a  
> function
> I want to be able to run:
>
> "mysize" <- function() {
>    z <- sapply(ls(), function(w) object.size(get(w)))
>    as.matrix(rev(sort(z))[1:5])
> }
> mysize()
>
> When I test the lines inside the function it works fine:
>
>>    z <- sapply(ls(), function(w) object.size(get(w)))
>
>>    as.matrix(rev(sort(z))[1:5])
>             [,1]
> mat     166344288
> mod     130794704
> zidx       799664
> wfidx      799664
> megacap    799664
>>
>
> But when I try to run the function, it produces an error:
>
>> "mysize" <- function() {
> +     z <- sapply(ls(), function(w) object.size(get(w)))
> +     as.matrix(rev(sort(z))[1:5])
> + }
>
>> mysize()
> Error in rev(sort(z)) :
>  error in evaluating the argument 'x' in selecting a method for
> function 'rev': Error in sort.int(x, na.last = na.last, decreasing =
> decreasing, ...) :
>  'x' must be atomic
>>
>
> It must be a variable scoping problem, but I am not sure how to tackle
> it.

I would have called it a function scoping problem. Inside the function  
ls() will not "see" the global environment unless you tell it where to  
look. (It may even be two levels deeper than the globalenv() when  
called inside `sapply`.) When called without an environment, it just  
looks in parent.frame which is inside the function.

"mysize" <- function() {
      z <- sapply(ls(env=globalenv()), function(w) object.size(get(w)))
      as.matrix(rev(sort(z))[1:5])
  }

#works for me.


--
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list