[R] Using object.size inside a function

2010-04-13 Thread Bos, Roger
When I encounter memory errors, I like to see the size of the objects in
memory, so I modified one of the examples:

z - sapply(ls(), function(x) object.size(get(x)))
as.matrix(rev(sort(z))[1:10])

This works fine if I run it as is, but if I try to place it inside a
function, I get an error (see below).  I tried using sort.list and
unlist, but I couldn't get it to work.  I don't understand why the
commands work by themselves but not in a function.  Its probably a
simple fix, can anyone enlighten me?

Thanks, Roger.

 mysize - function() {
+ z - sapply(ls(), function(x) object.size(get(x)))
+ as.matrix(rev(sort(z))[1:10])
+ }

 mysize()
Error in sort.list(z) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?
 
***

This message is for the named person's use only. It may\...{{dropped:20}}

__
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.


Re: [R] Using object.size inside a function

2010-04-13 Thread Duncan Murdoch

On 13/04/2010 8:43 AM, Bos, Roger wrote:

When I encounter memory errors, I like to see the size of the objects in
memory, so I modified one of the examples:

z - sapply(ls(), function(x) object.size(get(x)))
as.matrix(rev(sort(z))[1:10])

This works fine if I run it as is, but if I try to place it inside a
function, I get an error (see below).  I tried using sort.list and
unlist, but I couldn't get it to work.  I don't understand why the
commands work by themselves but not in a function.  Its probably a
simple fix, can anyone enlighten me?

Thanks, Roger.

 mysize - function() {
+ z - sapply(ls(), function(x) object.size(get(x)))
+ as.matrix(rev(sort(z))[1:10])
+ }

 mysize()
Error in sort.list(z) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?
 
At the time you call ls(), you have no local variables, so it returns an 
empty list, and z ends up as list().  sort() can't handle that.


I imagine you wanted ls() on the global environment, not on the locals, 
so you should write the function as


mysize - function(envir=globalenv()) {
   z - sapply(ls(envir=envir), function(x) object.size(get(x,envir=envir)))
   as.matrix(rev(sort(z))[1:10])
}

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.