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

Henrik Bengtsson hb at maths.lth.se
Fri Jul 22 09:32:12 CEST 2005

```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)
if (USE.NAMES && is.character(X) && is.null(names(answer)))
if (simplify && length(answer) && length(common.len <-
if (common.len == 1)
else if (common.len > 1)
dim = c(common.len, length(X)),
dimnames = if (!(is.null(n1 <- names(answer[[1]]))
list(n1, n2))
}
}

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)