[R] Confused: Inconsistent result?

Petr PIKAL petr.pikal at precheza.cz
Mon Feb 20 16:21:50 CET 2012


Hi
> 
> This is copy & paste from my session:
> 
> > xyz<-as.vector(c(ls(),as.matrix(lapply(ls(),class))))
> > dim(xyz)<-c(length(xyz)/2,2)
> > 
> > allobj<-function(){
> + xyz<-as.vector(c(ls(),as.matrix(lapply(ls(),class))));
> + dim(xyz)<-c(length(xyz)/2,2);
> + return(xyz)
> + }
> > xyz
>       [,1]              [,2]       
>  [1,] "a"               "character"
>  [2,] "aa"              "character"
>  [3,] "abc"             "character"
>  [4,] "AirPassengers"   "character"
>  [5,] "allobj"          "character"
>  [6,] "allObjects"      "character"
>  [7,] "allObjects2"     "character"
>  [8,] "arrayFromAPL"    "character"
>  [9,] "classes"         "character"
> [10,] "myCharVector"    "character"
> [11,] "myDateVector"    "character"
> [12,] "myNumericVector" "character"
> [13,] "newArrayFromAPL" "character"
> [14,] "obj"             "character"
> [15,] "objClass"        "character"
> [16,] "x"               "character"
> [17,] "xyz"             "character"
> [18,] "y"               "character"
> > allobj()
>      [,1] [,2]
> > 
> 
> As far as I can see, the function allobj has the same expressions as 
those
> executed from the command line. Why are the results different?

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
}







>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> 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