Skip to content

Confused: Inconsistent result?

5 messages · Ajay Askoolum, David Winsemius, R. Michael Weylandt +1 more

#
On Feb 20, 2012, at 10:07 AM, Ajay Askoolum wrote:

            
The ls function looks only in the local environment if not supplied  
with specific directions about where to look.
David Winsemius, MD
West Hartford, CT
#
Short answer, environments -- ls() looks (by default) in its current
environment, which is not the same as the global environment when
being called inside a function.

This would (I think) give the same answer but I haven't checked it. :
+ xyz<-as.vector(c(ls(.GlobalEnv),as.matrix(lapply(ls(),class))));
+ dim(xyz)<-c(length(xyz)/2,2);
+ return(xyz)
+ }
On Mon, Feb 20, 2012 at 10:07 AM, Ajay Askoolum <aa2e72e at yahoo.co.uk> wrote:
#
Sorry, just checked it and you need to add ".GlobalEnv" to both ls() calls.


Michael

On Mon, Feb 20, 2012 at 10:17 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
#
Hi
those
Probably due to environment handling. 

Do you really want to check if ls behaves as is intended and that it 
produces character vector? Or your intention is a little bit more 
ambitious and you want to know what objects do you have?

If the later, I recommend to use this function:

function (pos = 1, pattern, order.by) 
{
    napply <- function(names, fn) sapply(names, function(x) fn(get(x, 
        pos = pos)))
    names <- ls(pos = pos, pattern = pattern)
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)
    obj.dim <- t(napply(names, function(x) as.numeric(dim(x))[1:2]))
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by)) 
        out <- out[order(out[[order.by]]), ]
    out
}
http://www.R-project.org/posting-guide.html