[R] [FORGED] Having trouble understanding the sapply/vapply documentation and behaviour of USE.NAMES
Rolf Turner
r@turner @end|ng |rom @uck|@nd@@c@nz
Fri Apr 10 02:23:49 CEST 2020
On 10/04/20 10:59 am, petr smirnov wrote:
> 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?
IMHO there is an error in the documentation here. Clearly USE.NAMES has
a different impact on vapply() than it has on sapply() and the
documentation does not indicate this, in fact quite the opposite.
It might be appropriate to submit a bug report (see
https://www.r-project.org/bugs.html) but it's probably not worth the
hassle. It's a pretty minor error.
cheers,
Rolf Turner
--
Honorary Research Fellow
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276
More information about the R-help
mailing list