[R] Having trouble understanding the sapply/vapply documentation and behaviour of USE.NAMES

petr smirnov p@m|rnov2000 @end|ng |rom gm@||@com
Fri Apr 10 00:59:04 CEST 2020


I am having trouble parsing the documentation for sapply and vapply,
and I cannot understand if it explains the different behaviour of
USE.NAMES between the two.

I noticed the following different behaviour between the two functions:

> sapply(c("1"=1, "2"=2, "3"=3), function(x) {r <- list(x); r}, USE.NAMES=FALSE)
$`1`
[1] 1

$`2`
[1] 2

$`3`
[1] 3

> vapply(c("1"=1, "2"=2, "3"=3), function(x) { r <- list(x); r}, FUN.VALUE=list(1), USE.NAMES=FALSE)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

In the sapply case, the names of the input vector are retained. In the
vapply case, they are dropped. Note that this is not true when
USE.NAMES=TRUE:

> vapply(c("1"=1, "2"=2, "3"=3), function(x) { r <- list(x); r}, FUN.VALUE=list(1), USE.NAMES=TRUE)
$`1`
[1] 1

$`2`
[1] 2

$`3`
[1] 3

The manual page explains this for the names of the result of vapply:

The (Dim)names of the array value are taken from the FUN.VALUE if it
is named, otherwise from the result of the first function call. Column
names of the matrix or more generally the names of the last dimension
of the array value or names of the vector value are set from X as in
sapply.


If this explains the behaviour, could someone break it down for me and
help me understand the reasoning?
Otherwise, is this different behaviour intentional? Should it be
documented more clearly?

Thank you in advance!
-- 
Petr Smirnov
Department of Medical Biophysics, University of Toronto
Princess Margaret Cancer Centre, University Health Network



More information about the R-help mailing list