[R] sapply(NULL, ...) returns a list?!?

From: Henrik Bengtsson <hb_at_maths.lth.se>
Date: Fri 22 Jul 2005 - 17:32:12 EST


Hi,

I bet this one has be asked before, but doing

  sapply(x, FUN=as.character)

where 'x' is a vector, then the result "should [] be simplified to a vector" according to ?sapply, correct? However,

> x <- 1:10
> sapply(x, FUN=as.character)

  [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
> sapply(x[1], FUN=as.character)

  [1] "1"

But,

> sapply(x[c()], FUN=as.character)

  list()

or equivalent,

> sapply(NULL, FUN=as.character)

  list()

Please enlight me if I missed the reason for this.

Looking at the code for sapply(),

> sapply
function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) {

     FUN <- match.fun(FUN)
     answer <- lapply(as.list(X), FUN, ...)
     if (USE.NAMES && is.character(X) && is.null(names(answer)))
         names(answer) <- X
     if (simplify && length(answer) && length(common.len <-
                  unique(unlist(lapply(answer, length)))) == 1) {
         if (common.len == 1)
             unlist(answer, recursive = FALSE)
         else if (common.len > 1)
             array(unlist(answer, recursive = FALSE),
                   dim = c(common.len, length(X)),
                   dimnames = if (!(is.null(n1 <- names(answer[[1]]))
                                  & is.null(n2 <- names(answer))))
                              list(n1, n2))
         else answer
     }
     else answer

}

I see that the above behavior is coded for (because of the "&& length(answer) &&" statement), but is this wanted? I would like to get a vector of length zero, in line with

   if (simplify && length(X) == 0)
     answer <- FUN(X, ...)
   else
     answer <- lapply(as.list(X), FUN, ...)

Cheers

Henrik



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Jul 22 17:38:19 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:33:55 EST