Java Mailing List Archive

http://www.r-help.com/

Home » Home (12/2007) » R Help for Statistical Computing »

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

Henrik Bengtsson

2005-07-22

Replies:

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@(protected)
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
©2008 r-help.com - Jax Systems, LLC, U.S.A.